Using ZfcUser and BjyAuthorize to show or hide views - zend-framework2

I have recently installed ZfcUser and BjyAuthorize and would like to use them to show or hide various parts of the layout.phtml file.
I understand that BjyAuthorize is a firewall of sorts and the flowchart from git hub suggests it should be possible to get current permission status and to use that to hide or show a particular section of code.
So for instance:
<ul>
<li>Admin Menu item</li>
<li>Affiliate menu item</li>
<li>Guest Menu item</li>
</ul>
If an admin user is logged in, he will view all three items, the affiliate will only see Affiliate and guest and the guest will only see guest.
How I was thinking of doing this was something like this:
<?php
//Get array of permissions for current user *not certain how to do this*
$permissionArray = $this->GetBjyPermissions($current->user);
?>
<ul>
<?php if in_array('admin',$permissionArray) {?>
<li>Admin Menu item</li>
<?php } ?>
<?php if in_array('affiliate',$permissionArray) {?>
<li>Affiliate Menu item</li>
<?php } ?>
<li>Guest Menu item</li>
</ul>
Essentially this will allow me to hide the sections of code a user is not allowed to use.
If it is not possible to get the permissions via Bjy or Zfc I guess my option would be to simply query the Database and build a permissions array from that directly.
Has anyone else had to do something like this? Is this approach a good approach or is there another way of achieving this?
Many thanks for any input.

You can use the BjyAuthorize's IsAllowed view Helper. It knows the current user's identity, so you just have to check the rule. It works like:
$isMenuAdmin = $this->isAllowed( 'menu', 'menu_admin' );
$isMenuAffiliate = $this->isAllowed( 'menu', 'menu_affiliate' );
$isMenuGuest = $this->isAllowed( 'menu', 'menu_guest' );
menu is a resource and menu_* a rule. You have to define them in the bjyauthorize.global.php. I'd do it this way:
(...)
'resource_providers' => array(
'BjyAuthorize\Provider\Resource\Config' => array(
'menu' => array(),
),
),
'rule_providers' => array(
'BjyAuthorize\Provider\Rule\Config' => array(
'allow' => array(
/*
[0] -> role
[1] -> resource
[2] -> rule
*/
array( array( 'admin' ), 'menu', array( 'menu_admin' ) ),
array( array( 'affiliate' ), 'menu', array( 'menu_affiliate' ) ),
array( array( 'guest' ), 'menu', array( 'menu_guest' ) ),
),
),
),
(...)
BTW, it seems that you're trying to build a menu. I recommend you to check this post about integrating Zend Navigation with BjyAutorize.

Related

ZEND_Auth, deactivate navigation area

I´ve built a Login Page using Zend_Auth. Now my question ist how can I deactivate areas which are loaded with my layout.phtml?
Here the part of my code of my layout.phtml which I don´t want to see in my login and logout forms:
<div id="navigation">
<ul>
<li>Arbeitskalender</li>
<li>Arbeitskalender download</li>
<!--<li>Bibliothek</li> -->
<!-- <li>Schwestern</li> -->
</ul>
</div>
How can I work with different layouts? In which place and how can I load them?
You can have multiple layouts in an application. If you create another without the navigation HTML and configure it in your module.config.php, you can simply select which layout to use from within the controller.
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'layout/layout_login' => __DIR__ . '/../view/layout/layout_login.phtml'
)
Then in your controller:
$this->layout('layout/layout_login');
EDIT:
Alternatively if you'd like to dynamically change your layout you can use the Identity View Helper to check whether a user is logged in or not. e.g.
<!-- if logged in, show logout link -->
<?php if (null !== $this->identity()) : ?>
Logout
<?php endif; ?>

Render mail templete zend framework 2

i'm trying to sent an email with a template in Zend framework 2 applicatio.
This is code in my class called "EmailService...".
$view = new PhpRenderer();
$resolver = new TemplateMapResolver();
$resolver->setMap(array(
'mailTemplate' => __DIR__ . '/../../../mail/' . $template['name'] . '.phtml'
));
$view->setResolver($resolver);
$viewModel = new ViewModel();
$viewModel->setTemplate('mailTemplate')
->setVariables(
(!empty($template['variables']) && is_array($template['variables'])) ? $template['variables'] : array()
);
$this->_message->addFrom($this->_emailConfig['sender']['address'], $this->_emailConfig['sender']['name'])
->addTo($user['email'], $user['login'])
->setSubject($subject)
->setBody($view->render($viewModel))
->setEncoding('UTF-8');
Everything work fine but in this templete file I have to create a link to an action (I have specify route for this). But here is a problem. Becouse when I'm trying to use
<?php echo $this->url('auth') ; ?>
I've got "No RouteStackInterface instance provided" error.
If I use:
<?php echo $this->serverUrl(true); ?>
everything work fine... Any clue?
You shouldn't need to create a new instance of the PhpRenderer; you can just reuse the already created one.
$renderer = $this->serviceManager->get('viewrenderer');
$variables = is_array($template['variables']) ? $template['variables'] : array();
$viewModel = new ViewModel($variables);
$viewModel->setTemplate('mailTemplate');
$html = $renderer->render($viewModel);
In order to follow good DI practice, inject the PhpRenderer into the email service's __construct (rather than the service manager).
Also, the template path can be added in the normal module.config.php
return array(
'view_manager' => array(
'template_map' => array(
'mailTemplate' => __DIR__ . '/../view/foo/bar.phtml',
),
),
);
There are a lot of modules which make things easy when sending html mails. You can search them here.
My personal favourite is MtMail. You can easily use templates and layouts. You can easily set default headers(From, Reply-To etc.). You can use this Template Manager feature to better organize e-mail templates in object-oriented manner.
MtMail Usage:
$mailService = $this->getServiceLocator()->get('MtMail\Service\Mail');
$headers = array(
'to' => 'johndoe#domain.com',
'from' => 'contact#mywebsite.com',
);
$variables = array(
'userName' => 'John Doe',
);
$message = $mailService->compose($headers, 'application/mail/welcome.phtml', $variables);
$mailService->send($message);

How to adapt this wordpress loop query code to include pagination?

I have sourced the below code to query my posts in Wordpress and all works as intended.
I'd like to add pagination to this now. I don't want to alter the code too much now that I know it works, can anyone advise on the best way to adapt this to include the pagination?
I would like it to show a maximum of 18 posts per page and have next and prev links to other pages if they exist. This code is being used in custom category templates, but I have also setup a static page setup under the reading settings and the display of main posts uses home.php, I'd like to use the same or similar loop code to also paginate that. Any help is appreciated. Here is the code:
<div id="Items">
<ul>
<?php
// Grid sorted alphabetically
if (is_category('categoryName'))
{
$args = array( 'posts_per_page' => -1, 'orderby'=> 'title', 'order' => 'ASC', 'category' => 41 );
$categoryNameposts = get_posts( $args );
}
foreach( $categoryNameposts as $post ) : setup_postdata($post);
?>
<li><?php get_template_part( 'content', get_post_format() ); ?></li>
<?php endforeach; ?>
</ul>
</div><!-- #ItemsEnd -->
You should let wordpress know how much post you want to show per page in the query_posts. Replace your $args with these two lines:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'posts_per_page' => 18, 'paged' => $paged, 'orderby'=> 'title', 'order' => 'ASC', 'category' => 41 );
Now to show Next-Previous link:
<div class="paginationClass">
<?php next_posts_link(); ?>
<?php previous_posts_link(); ?>
</div>
Also in is_category function, use categorySlug, instead of categoryName.

Multi navigation failed in layout

why second var_dump() display null in this code in my layout.phtml :
var_dump(($this->navigation('navigation')->menu()->render()));
var_dump(($this->navigation('navigation')->breadcrumbs()->render()));
output :
string '<ul class="navigation">
<li>
DashBoard
</li>
<li>
Members Management
</li>
<li class="active">
Events
<ul>
<li>
Categories
</li>
<li class="active">
Show All
</li>
<li class="active">
<a href='... (length=802)
string '' (length=0)
EDIT :
actually changing var_dump order ... OMG ... again the second one is NULL !! :-O
Output :
string 'Events > Show All' (length=51)
string '' (length=0)
There was a bug in zf2 ver <= 2.1.3 about this and its closed but not yet merged into production package and will be fixed in next minor release
https://github.com/zendframework/zf2/issues/3976
Simple solution :
https://github.com/froschdesign/zf2/commit/454439d35716ed2125a6ac90c826836f57391eb0
the contents on breadcrumbs will depends where the output is executed.
for example, if you are inside a controller and action which has been assigned to one of your navigation items, then it should be picked up.
I suspect you haven't setup navigation pages for the controller/action pairing where you are performing the var_dump.
Example nav config:
array(
'navigation' => array(
'default' => array(
array(
'label' => 'Page One',
'route' => 'myroute',
'controller' => 'categories',
'action' => 'list',
),
If you perform your output in the listAction method of your Categories controller then the breadcrumb helper should return something for you

putting jquery buttons in clistview widget in yii

I am trying to put a button which will be displayed along with some data in the view file I specified in "itemView" field of the CListView widget, but instead of the styled button for every list item, I am just getting it or the first list item. My code in the _view file is:
<div id="listView">
<div class="thedata">
...some data
</div>
<div id="buttons">
<?php
$this->widget('zii.widgets.jui.CJuiButton', array(
'buttonType'=>'button',
'name'=>'btnJobs',
'caption'=>'Manage Jobs',
'options'=>array('icons'=>'js:{primary:"ui-icon-wrench"}'),
'onclick'=>'js:function(){alert("Manage Jobs clicked."); this.blur(); return false;}',
));
?>
</div>
</div>
and the code for CListView widget is just the bare minimum:
$this->widget('zii.widgets.CListView', array(
'dataProvider' => $dataProvider,
'itemView' => '_view'
));
any suggestions?
Try passing in a unique ID to the CJuiButton, like so:
<?php
$this->widget('zii.widgets.jui.CJuiButton', array(
'id'=>'button'.$data->id, // add a unique ID here (could use $index instead of $data->id)
'buttonType'=>'button',
'name'=>'btnJobs',
'caption'=>'Manage Jobs',
'options'=>array('icons'=>'js:{primary:"ui-icon-wrench"}'),
'onclick'=>'js:function(){alert("Manage Jobs clicked."); this.blur(); return false;}',
));
?>
The problem is that since all of your buttons have the same 'name' (and therefore 'id') jQuery is only binding to the first one. Making sure each button has a unique ID should fix this, so jQuery will bind correctly.

Resources