ZF2 - Multi navigation with navigation - zend-framework2

Is it possible to have 2 differents navigation ?
For example :
//in module.config.php
'service_manager'=>array(
'factories'=>array(
'navigation1'=>'Zend\Navigation\Service\DefaultNavigationFactory',
'navigation2'=>'Zend\Navigation\Service\DefaultNavigationFactory',
),
),
'navigation'=>array(
'navigation1'=>array(
'home'=>array('type' => 'mvc','route' => 'home','active'=>false,'label' => 'Home','title' => 'Home',
'pages'=>array(
'contact'=>array('type' => 'mvc','route'=>'contact','active'=>false,'label'=>'Contact','title' =>'Contact'),
)
),
),
'navigation2'=>array(
'home'=>array('type'=>'mvc','route'=>'home','active'=>false,'label'=>'Home','title'=>'Home',
'contact'=>array('type'=>'mvc','route'=>'faq','active'=>false,'label'=>'Faq','title'=>'Faq'),
),
),
//Dans laout
<?php echo $this->navigation()->menu('navigation1')->setMinDepth(0);?>
<hr />
<?php echo $this->navigation()->menu('navigation2')->setMinDepth(0);?>
I would like 2 differents menu with differents pages but this method doesn't run.
Every one has an idea please ?
Thanks
Birzat

You need to provide a custom factory class for each navigation group. For example, see how ZfcAdmin does this:
Create a custom factory class
<?php
namespace ZfcAdmin\Navigation\Service;
use Zend\Navigation\Service\DefaultNavigationFactory;
class AdminNavigationFactory extends DefaultNavigationFactory
{
protected function getName()
{
return 'admin';
}
}
Source: https://github.com/ZF-Commons/ZfcAdmin/blob/master/src/ZfcAdmin/Navigation/Service/AdminNavigationFactory.php
Register AdminNavigationFactory
// in Module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'admin_navigation' => 'ZfcAdmin\Navigation\Service\AdminNavigationFactory',
),
);
}
Source: https://github.com/ZF-Commons/ZfcAdmin/blob/master/Module.php#L90
Define Navigation trees in your module's configuration under the key you specified in the getName method of your factory. As an example, this is how ZfcUserAdmin adds itself to the ZfcAdmin menu:
'navigation' => array(
'admin' => array(
'zfcuseradmin' => array(
'label' => 'Users',
'route' => 'zfcadmin/zfcuseradmin/list',
'pages' => array(
'create' => array(
'label' => 'New User',
'route' => 'admin/create',
),
),
),
),
),
Source: https://github.com/Danielss89/ZfcUserAdmin/blob/master/config/module.config.php

/vendor/MyNamespace/library/MyNamespace/Navigation/Service/SecondaryNavigationFactory.php
namespace MyNamespace\Navigation\Service;
use Zend\Navigation\Service\DefaultNavigationFactory;
class SecondaryNavigationFactory extends DefaultNavigationFactory {
protected function getName() {
return 'secondary';
}
}
/config/autoload/global.php
return array(
'service_manager' => array(
'factories' => array(
'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory',
'secondary' => 'MyNamespace\Navigation\Service\SecondaryNavigationFactory',
),
),
'navigation' => array(
'default' => array(
array(
'label' => 'Item-1.1',
'route' => 'foo',
),
array(
'label' => 'Item-1.2',
'route' => 'bar',
),
),
'secondary' => array(
array(
'label' => 'Item-2',
'route' => 'baz',
),
),
),
);
/module/Application/view/layout/layout.phtml
<?php echo $this->navigation('navigation')->menu(); ?>
<?php echo $this->navigation('secondary')->menu(); ?>

Related

Zend framework2 multi controller in module

I've got a problem with adding many controllers in the one module. Zend2 is difficult for beginners.
I've created Module "Home" with Controllers "Home" and "News". HomeController is going fine but when I'm trying to connect to the NewsController I'm getting Fatal error: Class 'Home\Controller\NewsController' not found in C:\wamp\www\zend2\vendor\zendframework\zendframework\library\Zend\ServiceManager\AbstractPluginManager.php on line 170. And I don't know where the problem is.
My module.config looks like
return array(
'controllers' => array(
'invokables' => array(
'Home\Controller\Home' => 'Home\Controller\HomeController',
'Home\Controller\News' => 'Home\Controller\NewsController',
),
),
'router' => array(
'routes' => array(
'home' => array(
'type' => 'segment',
'options' => array(
'route' => '/home[/][:action]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*'
),
'defaults' => array(
'controller' => 'Home\Controller\Home',
'action' => 'index',
),
),
),
'news' => array(
'type' => 'segment',
'options' => array(
'route' => '/news[/][:action]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*'
),
'defaults' => array(
'controller' => 'Home\Controller\News',
'action' => 'index',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'album' => __DIR__ . '/../view',
),
),
);
I'm using navigation factory so navigation file looks like :
return array(
'navigation' => array(
'default' => array(
array(
'label' => 'Home',
'route' => 'home'
),
array(
'label' => 'News',
'route' => 'news'
),
),
),
'service_manager' => array(
'factories' => array(
'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory'
)
)
);
And Module.php looks like
namespace Home;
class Module {
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
}
And NewsController looks like
namespace News\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class NewsController extends AbstractActionController {
public function indexAction()
{
return array();
}
}
In your controller class you're declaring the namespace as:
namespace News\Controller;
yet in your module config you list the invokable class as Home\Controller\NewsController. The namespaces need to match, so you probably want to change the controller class namespace to:
namespace Home\Controller;

ZendFramework 2: No database adapter present

I have this class:
<?php
class RegisterFilter extends InputFilter
{
public function __construct()
{
$this->add(array(
'name' => 'email1',
'required' => true,
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
),
array(
'name' => 'Identical',
'options' => array(
'token' => 'email2',
),
),
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'user',
'field' => 'email',
'messages' => array(
'recordFound' => "Email already exist ... ! <br>",
),
),
),
),
));
}
}
?>
I get this error: No database adapter present. Any ideas why this happens?
It would be good if you'd read the documentation about Zend\Validator\Db\Record*. The given error message means exactly what it said. You don't provide a DB-Adapter inside the Validator.
From the DOCs:
$validator = new Zend\Validator\Db\RecordExists(
array(
'table' => 'users',
'field' => 'emailaddress',
'adapter' => $dbAdapter
)
);
If you want to find out how to get the DB-Adapter into your Form, i have written a Blog Article about said topic.

ServiceNotCreatedException in Zend Framework 2 while attempting multiple navigations

I am attempting to create multiple navigation menus to use in my application based on a specific user role. The majority of the code is similar to zfc-admin. When I use zfc-admin in my application I am able to bring up an admin menu, however I will have about four roles, and decided to put this in my Application module.
module.config.php
'navigation' => array(
'admin' => array(
array(
'label' => 'Admin Home',
'route' => 'adminhome',
),
),
'default' => array(
array(
'label' => 'Home',
'route' => 'home',
),
),
),
AdminNavigationFactory.php
namespace Application\Navigation\Service;
use Zend\Navigation\Service\DefaultNavigationFactory;
class AdminNavigationFactory extends DefaultNavigationFactory
{
protected function getName()
{
return 'admin';
}
}
Module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'admin_navigation' => 'Application\Navigation\Service\AdminNavigationFactory',
),
);
}
layout.phtml
<?php echo $this->navigation('admin_navigation')->menu(); ?>
I get the error.
Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotCreatedException' with message 'While attempting to create adminnavigation(alias: admin_navigation) an invalid factory was registered for this instance type.' in /Applications/MAMP/htdocs/myapp/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 987
If I change the layout.phtml to use the default menu everything works as expected.
<?php echo $this->navigation('navigation')->menu(); ?>
first I got exactly the same issue. After moving the factory configuration from the getServiceConfig() method in the module class to the module.config.php it worked.
So my admin navigation works now like the follows:
module.config.php
(module/Admin/config/module.config.php)
return array(
// yada yada yada...
'service_manager' => array(
'factories' => array(
'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory',
'adminnav' => 'Application\Navigation\Service\AdminNavigationFactory',
),
),
'navigation' => array(
'default' => array(
array(
'label' => 'Home',
'route' => 'home',
),
array(
'label' => 'Filme',
'route' => 'movies',
),
array(
'label' => 'Admin',
'route' => 'admin',
),
),
'adminnav' => array(
array(
'label' => 'Film hinzufügen',
'route' => 'add-movie',
),
array(
'label' => 'Buch hinzufügen',
'route' => 'add-book',
),
),
),
);
AdminNavigationFactory
(module/Application/src/Application/Navigation/Service/AdminNavigationFactory.php)
namespace Application\Navigation\Service;
use Zend\Navigation\Service\DefaultNavigationFactory;
class AdminNavigationFactory extends DefaultNavigationFactory
{
protected function getName()
{
return 'adminnav';
}
}
Maybe you want to check out the code in context of the entire application, so here are the links to the my github:
AdminNavigationFactory
module.config.php
Regards,
Sascha

custom routing for content pages in zf2

Hello to all zend coders. I am newbie to zend, doing code for manage pages through DB.
I want to use URL for these pages like this:
www.domainname.com/about-us
www.domainname.com/contact-us
...
Table name is 'cms_page' & attributes are:
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`page_key` varchar(255) NOT NULL,
`content` longtext NOT NULL,
`added_on` datetime NOT NULL,
I have done R&D for this and here are code:
// in module.config.php
'navigation' => array(
'default' => array(
'account' => array(
'label' => 'Account',
'route' => 'node',
'params' => array(
'id' => '2',
),
'pages' => array(
'home' => array(
'label' => 'Dashboard',
'route' => 'node',
'params' => array(
'id' => '1',
'link' => '/test'
),
),
'login' => array(
'label' => 'Sign In',
'route' => 'node',
'params' => array(
'id' => '5',
'link' => '/about-us'
),
),
'logout' => array(
'label' => 'Sign Out',
'route' => 'node',
'params' => array(
'id' => '3',
),
),
),
),
),
),
'router' => array(
'routes' => array(
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
),
'node' => array(
'type' => 'Application\Router\Alias',
'options' => array(
'route' => '/node[/:id]',
'constraints' => array(
'id' => '[0-9]+'
),
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
'id' => '0'
),
),
'may_terminate' => true,
),
),
),
// In Module.php
public function onBootstrap(MvcEvent $e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
$sm->get('translator');
$sm->get('viewhelpermanager')->setFactory('controllerName', function($sm) use ($e) {
$viewHelper = new View\Helper\ControllerName($e->getRouteMatch());
return $viewHelper;
});
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$sm->setFactory('Navigation', 'Zend\Navigation\Service\DefaultNavigationFactory', true);
$alias = $sm->get('Application\Router\Alias');
$nav = $sm->get('Navigation');
$alias->setNavigation($nav);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Router\Alias' => function($sm) {
$alias = new \Application\Router\Alias('/node[/:id]');
return $alias;
},
)
);
}
// Application\src\Application\Router
namespace Application\Router;
use Traversable;
use Zend\Mvc\Router\Exception;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Mvc\Router\Http;
use Zend\Mvc\Router\Http\Segment as Segment;
class Alias extends Segment
{
private static $_navigation = null;
public function match(Request $request, $pathOffset = null)
{
$uri = $request->getUri();
$path = $uri->getPath();
$items = self::$_navigation->findAllBy('route', 'node');
$params = null;
if($items != null){
$t = sizeof($items);
for ($i=0; $i getParams();
if (isset($params['link']) && $params['link']==$path){
echo $uri->setPath('/'.$item->getRoute().'/'.$params['id']);
$request->setUri($uri);
break;
}
}
}
return parent::match($request, $pathOffset);
}
public function setNavigation($navigation){
self::$_navigation = $navigation;
}
protected function buildPath(array $parts, array $mergedParams, $isOptional, $hasChild, array $options)
{
if(isset($mergedParams['link'])){
return $mergedParams['link'];
}
return parent::buildPath($parts, $mergedParams, $isOptional, $hasChild, $options = array());
}
}
When I run this url www.domainname.com/about-us on browser getting 404 error.
Please help me where am I wrong and what code need to add or edit?
You can use the a Zend_Controller_Router_Route as an alternative. Here is a quick tutorial on how to do so:
http://www.codexperience.co.za/post/hiding-url-parameters-names-using-zend-routers

How To Create Custom Form Elements That Extend Doctrine Entity Select Elements

I am trying to create a custom element where I can pre-set an entity namespace say -- Application\Entity\User and easily add that element to any form. I have an issue with injecting the doctrine em in form elements -- I found this post about the form_elements key in configuration but it doesnt work -- so I figured maybe just setup the element and pass it the objectmanager from the form.
I want to do something like this.
$this->add(
array(
'name' => 'user_id',
'type' => 'Application\Form\Element\UserSelect',
'options' => array(
'label' => 'User',
'object_manager' => $this->getObjectManager(),
),
),
);
Or even better just this
$this->add(
array(
'name' => 'user_id',
'type' => 'Application\Form\Element\UserSelect',
'label' => 'User',
),
);
module.config.php
'service_manager' => array(
'aliases' => array(
'doctrine_service' => 'doctrine.entitymanager.orm_default',
),
'initializers' => array(
function ($instance, $sm) {
if ($instance instanceof DoctrineModule\Persistence\ObjectManagerAwareInterface) {
$instance->setObjectManager(
$sm->get('doctrine_service')
);
}
if ($instance instanceof Application\Form\AbstractForm) {
$instance->init();
}
},
),
),
AbstractForm.php
namespace Application\Form;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Zend\Form\Form as ZendForm;
abstract class AbstractForm extends ZendForm implements ObjectManagerAwareInterface
{
protected $objectManager;
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
public function getObjectManager()
{
return $this->objectManager;
}
}
TestForm.php
namespace Users\Form;
use Application\Form\AbstractForm;
class Login extends AbstractForm
{
public function init()
{
$this->add(
array(
'name' => 'user_id',
'type' => 'DoctrineORMModule\Form\Element\DoctrineEntity',
'options' => array(
'label' => 'User',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Application\Entity\User',
'property' => 'name',
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('is_deleted' => 0),
'orderBy' => array('name' => 'ASC'),
),
),
),
),
);
}
}
Add your initializer and invokables to the getFormElementConfig method of your Module.php:
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
...
public function getFormElementConfig()
{
return array(
'invokables' => array(
'MyForm' => 'Application\Form\MyForm',
),
'initializers' => array(
'ObjectManagerInitializer' => function ($element, $formElements) {
if ($element instanceof ObjectManagerAwareInterface) {
$services = $formElements->getServiceLocator();
$entityManager = $services->get('Doctrine\ORM\EntityManager');
$element->setObjectManager($entityManager);
}
},
),
);
}
Then use the FormElementManager to get te form:
$forms = $this->getServiceLocator()->get('FormElementManager');
$myForm = $forms->get('MyForm');
Finally add your element inside the init method - not the constructor because he will never be aware of the objectManager:
public function init()
{
$this->add(
array(
'name' => 'user_id',
'type' => 'DoctrineORMModule\Form\Element\DoctrineEntity',
'options' => array(
'label' => 'User',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Application\Entity\User',
'property' => 'name',
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('is_deleted' => 0),
'orderBy' => array('name' => 'ASC'),
),
),
),
),
);
}
See a discussion on this setup here.

Resources