Zend_Navigation add class to active link - php

How can I add a class to the active navigation link? If a link points to URI /index/index and the request URI is also /index/index, I would like the link to have class, for example:
<li class="active">
Index
</li>
This is how I am initializing navigation in the bootstrap:
protected function _initNavigation()
{
$navigation = new Zend_Navigation($this->getOption('navigation'));
$this->view->navigation($navigation);
}

Ok,
I have solved this by writing a controller plugin:
<?php
class My_Controller_Plugin_PrepareNavigation extends Zend_Controller_Plugin_Abstract
{
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer');
$viewRenderer->initView();
$view = $viewRenderer->view;
$container = new Zend_Navigation(Zend_Registry::get('configuration')->navigation);
foreach ($container->getPages() as $page) {
$uri = $page->getHref();
if ($uri === $request->getRequestUri()) {
$page->setClass('active');
}
}
$view->navigation($container);
}
}

This is how to create a navigation() in a layout() with zend frameworks using Application.
Well, at least one way of doing it. the CSS class is set on the
put this into the Bootstrap.php file:
protected function _initNavigation()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
include APPLICATION_PATH . '/layouts/scripts/menu.phtml';
$view->navigation($container);
}
This allows you to create an array for a menu in the file menu.phtml, so that you can still maintain the active class on the current link. For some strange reason, if you use this you must include the controller property in the array to get the CSS active class on the current link.
put something like this into the /layouts/scripts/menu.phtml file:
$container = new Zend_Navigation(array(
array(
'label' => 'HOME',
'id' => 'tasks',
'uri'=>'/',
'controller' => 'Index'
),
array(
'label' => 'Contact',
'uri' => 'contact',
'controller' => 'Contact'
),
.... more code here ...
put this into the layout.phtml file:
$options = array('ulClass' => 'menu');

Related

How to add new layout for admin dashboard

In Zend Expressive, the layout is "default" into "templates" folder.
I would like to add "admin" folder into "templates" folder like that:
Templates
admin
app
admin-page.phtml
error
404.phtml
error.phtml
layout
default.phtml
default
app
home-page.phtml
error
404.phtml
error.phtml
layout
default.phtml
I've tried with the tutorials of Zend expressive to add new layout but no success for me...
class AdminPageHandler implements RequestHandlerInterface
{
private $template;
public function __construct(TemplateRendererInterface $template)
{
$this->template = $template;
}
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$data = [
'admin' => 'layout::admin',
// or 'layout::admin',
// or 'layout::alternative',
];
$content = $this->template->render('pages::admin-page', $data);
return new HtmlResponse($content);
}
}
How can I add a new layout for my admin dashboard?
I would like to add new layout for my admin dashboard because the HTML script is different of my Home Application.
The template paths can be found in ConfigProvider class => __invoke method, under 'templates' => 'paths' or in getTemplates() method. There you should add a new path:
/**
* Returns the templates configuration
*/
public function getTemplates(): array
{
return [
'paths' => [
'app' => [__DIR__ . '/../templates/app'],
'error' => [__DIR__ . '/../templates/error'],
'layout' => [__DIR__ . '/../templates/layout'],
'admin' => [__DIR__ . '/../templates/admin'],
],
];
}
then your handler should look something like this
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$data = [
'admin' => 'layout::admin',
// or 'layout::admin',
// or 'layout::alternative',
];
$content = $this->template->render('admin::app/admin-page', $data);
return new HtmlResponse($content);
}

How to set routing in Zend Framework 1.12

My aim is to have product links like:
domain.com/test-product
domain.com/second-test-product
instead of:
domain.com/products/product/id/5
domain.com/products/product/id/123
Info about each product is get in ProductsController in productAction().
It works fine:
ProductsController:
public function productAction() {
$products = new Application_Model_DbTable_Products();
$nicelink = $this->_getParam('nicelink', 0);
$this->view->product = $products->fetchRow($products->select()->where('product_nicelink = ?', $nicelink));
// nicelink is always unique
}
The link to this method looks like:
for ($i=0; $i < count($this->products); $i++) {
echo 'LINK';
}
Info about each product is displayed in product.phtml view:
<?php echo $this->escape($this->product->product_name); ?>
And my Bootstrap.php file:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initRoutes() {
$router = Zend_Controller_Front::getInstance()->getRouter();
include APPLICATION_PATH . "/configs/routes.php";
//$frontController = Zend_Controller_Front::getInstance();
$route = new Zend_Controller_Router_Route_Regex(
'(.+)',
array(
'controller' => 'products',
'action' => 'product'
),
array(
1 => 'nicelink',
),
'%s.html'
);
$router->addRoute('profileArchive', $route);
}
}
However, this solution has 1 major disadvantage: all other links such as
domain.com/contact
domain.com/about-us
are not working (probably due to the Bootstrap file).
How to fix the problem in order to make another links work and maintain current product links?
The issue is that you are matching all routes to product action in products controller. Probably you want to keep using the default routes in zend 1, which match "contact" and "about-us" to the corresponding actions in your default controller.
If you check "Zend_Controller_Router_Rewrite" function "addDefaultRoutes()" and "route()", you can see that the default routes will be checked after any custom ones.
The simplest solution, looking on what you are asking would be to match any routes that end with "-product":
$route = new Zend_Controller_Router_Route_Regex(
'(.+)\-product',
array(
'controller' => 'products',
'action' => 'product'
),
array(
1 => 'nicelink',
),
'%s.html'
);
In this case nicelink should take values "test" and "second-test" in your corresponding examples.

How to configure cakephp custom route class

I have create custom router class in cakephp 2.x, I'm just follow this blog post. In my app i don't have /Routing/Route folders and I create folders and put StaticSlugRoute.php file to it. In that file include following code
<?php
App::uses('Event', 'Model');
App::uses('CakeRoute', 'Routing/Route');
App::uses('ClassRegistry', 'Utility');
class StaticSlugRoute extends CakeRoute {
public function parse($url) {
$params = parent::parse($url);
if (empty($params)) {
return false;
}
$this->Event = ClassRegistry::init('Event');
$title = $params['title'];
$event = $this->Event->find('first', array(
'conditions' => array(
'Event.title' => $title,
),
'fields' => array('Event.id'),
'recursive' => -1,
));
if ($event) {
$params['pass'] = array($event['Event']['id']);
return $params;
}
return false;
}
}
?>
I add this code but it didn't seems to working (event/index is working correct).I want to route 'www.example.com/events/event title' url to 'www.example.com/events/index/id'. Is there any thing i missing or i need to import this code to any where. If it is possible to redirect this type of ('www.example.com/event title') url.
Custom route classes should be inside /Lib/Routing/Route rather than /Routing/Route.
You'll then need to import your custom class inside your routes.php file.
App::uses('StaticSlugRoute', 'Lib/Routing/Route');
Router::connect('/events/:slug', array('controller' => 'events', 'action' => 'index'), array('routeClass' => 'StaticSlugRoute'));
This tells CakePhp to use your custom routing class for the URLs that look like /events/:slug (ex: /events/event-title).
Side Note: Don't forget to properly index the appropriate database field to avoid a serious performance hit when the number of rows increases.

Zend routing without controller and action

There are given article URLs in a database (e.g. "article1", "article2", "article3").
When I type www.example.com/article1 I want to route to
controller: index,
action:index.
My route is:
//Bootstrap.php
public function _initRoute(){
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$router->addRoute('index',
new Zend_Controller_Router_Route('article1', array(
'controller' => 'index',
'action' => 'index'
))
);
}
But when I click on another link (functional before), I get www.example.com/article1 again.
Is there any way to do this route generally for all URLs in database? Something like:
$router->addRoute('index',
new Zend_Controller_Router_Route(':article', array(
'controller' => 'index',
'action' => 'index'
))
);
I usually set up an ini file instead of going the xml route or "new Zend_controller_Router_Route" way. In my opinion its a little easier to organize. This is how I do what you are looking for. I recommend that make some changes to your routing and not use a route of http://domain.com/article1 but more like http://domain.com/article/1. either way here is what I would do in your situation.
In your routes.ini file
routes.routename.route = "route"
routes.routename.defaults.module = en
routes.routename.defaults.controller = index
routes.routename.defaults.action = route-name
routes.routename.defaults.addlparam = "whatevs"
routes.routename.route = "route2"
routes.routename.defaults.module = en
routes.routename.defaults.controller = index
routes.routename.defaults.action = route-name
routes.routename.defaults.addlparam = "whatevs2"
routes.route-with-key.route = "route/:key"
routes.route-with-key.defaults.module = en
routes.route-with-key.defaults.controller = index
routes.route-with-key.defaults.action = route-with-key
In your bootstrap file
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
#... other init things go here ...
protected function _initRoutes() {
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini');
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$router->addConfig($config,'routes');
$front->setRouter($router);
return $router;
}
}
In your controller you can then do this
class IndexController extends Zend_Controller_Action {
public function routeNameAction () {
// do your code here.
$key = $this->_getParam('addlparam');
}
public function routeWithKeyAction () {
$key = $this->_getParam('key');
// do your code here.
}
}

Setup Zend Router with and without lang uri parameter

I'm wondering if anyone can help me with the next issue I have.
I want to be able to setup my project with multilanguage support with and without Uri lang flag, and also, with module structure.
I mean something like
http://mydomain/
http://mydomain/forum
http://mydomain/gallery
Navigate without lang uri parameter with the Zend_Locale + Zend_Translate default (en)
And also :
http://mydomain/es
http://mydomain/es/forum
http://mydomain/es/gallery
I've followed some tutos that I've found, but I still can't do so.
This is my current code :
I have zend _initRoute, _initLocale and _initTranslate setted on my bootstrap.php as follow:
protected function _initRoutes()
{
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$module = new Zend_Controller_Router_Route_Module(
array(),
$front->getDispatcher(),
$front->getRequest()
);
$language = new Zend_Controller_Router_Route(
':lang',
array(
'lang' => 'es'
)
);
/**
* I didn't chain this route cause doesn't work as I expected,
* but this is how I want to be able to navigate.
*
**/
$default = new Zend_Controller_Router_Route(
':controller/:action/*',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'index',
'action' => 'index'
)
);
$chainRoute = new Zend_Controller_Router_Route_Chain();
$chainRoute->chain($language)
->chain($module);
$router->addRoute('default', $chainRoute);
return $router;
}
/**
*
* Default locale: es_AR
*/
protected function _initLocale()
{
$local = new Zend_Locale();
$local->setDefault('es_AR');
Zend_Registry::set('Zend_Locale', $local);
}
/**
*
* Inisializacion de los lenguages y el Locale por default
*/
protected function _initTranslate()
{
$translate = new Zend_Translate(
'Array',
APPLICATION_PATH . "/langs/",
null,
array(
'scan' => Zend_Translate::LOCALE_DIRECTORY
)
);
Zend_Registry::set('Zend_Translate', $translate);
$translate->setLocale(Zend_Registry::get('Zend_Locale'));
}
I also register the next Language Plugin :
class MyApp_Controller_Plugin_Language extends Zend_Controller_Plugin_Abstract
{
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$lang = $request->getParam('lang', null);
$locale = Zend_Registry::get('Zend_Locale');
$translate = Zend_Registry::get('Zend_Translate');
if ($translate->isAvailable($lang)) {
$translate->setLocale($lang);
$locale->setLocale($lang);
} else {
//throw new Zend_Controler_Router_Exception('Translation language is not available', 404);
$lang = $locale->getLanguage();
$locale->setLocale($lang);
$translate->setLocale($lang);
}
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$router->setParam('lang', $lang);
}
}
Also I've created my own Url helper extended by zend url helper which uses the 'Language_Action_Helper':
class Zend_View_Helper_MyUrl extends Zend_View_Helper_Url
{
protected function _getCurrentLanguage()
{
return Zend_Controller_Action_HelperBroker::getStaticHelper('Language')
->getCurrent();
}
public function myUrl($urlOptions = array(), $name = null, $reset = true, $encode = true)
{
$urlOptions = array_merge(
array(
"lang" => $this->_getCurrentLanguage()
),
$urlOptions
);
return parent::url($urlOptions, $name, $reset, $encode);
}
}
And then I've created an Anchor helper which uses my url Helper :
class Zend_View_Helper_Anchor extends Zend_View_Helper_Abstract
{
public function anchor
(
$anchorText,
$controller,
$action,
Array $params = array()
)
{
$front = Zend_Controller_Front::getInstance();
$defaultUrl = array(
'module' => $front->getRequest()->getModuleName(),
'controller' => $controller,
'action' => $action
);
if (!empty($params)) {
foreach ($params as $param => $value) {
$defaultUrl[$param] = $value;
}
}
// using my url helper
$url = $this->view->myUrl(
$defaultUrl,
null,
true
);
$anchor =<<<HTML
{$anchorText}
HTML;
return $anchor;
}
}
This is the Language Action helper to provide the language inside the controller used by my url helper.
class Controller_Helper_Language extends Zend_Controller_Action_Helper_Abstract
{
/**
*
* Get Current language
*
* #return mixed string|null
*/
public function getCurrent(){
if (!Zend_Registry::isRegistered("Zend_Locale"))
return null;
return Zend_Registry::get("Zend_Locale")->getLanguage();
}
/**
*
* Get translator
*
* #return mixed Zend_Translate|null
*
*/
public function getTranslator(){
if (!Zend_Registry::isRegistered("Zend_Translate"))
return null;
return Zend_Registry::get("Zend_Translate");
}
}
My final approach is with this structure, be able to set up standard routes like :
http://mydomain/forum/:id
http://mydomain/topic/:id
http://mydomain/section/:id
http://mydomain/user/:user
with language support.
How these routes must be configured to meet my needs?, I mean, I've tried to do something like :
// what may I do here? How do I chain this route with my language router
$topicRoute = new Zend_Controller_Router_Route(
'topic/:id',
array(
'module' => 'default',
'controller' => 'forum',
'action' => 'topic',
'id' => ':id'
),
array(
'id' => '^[0-9]$'
)
)
Also this router config bring me some problems with my navigation config.
When I set this router, and then navigate to /topic/id, when I hover any link given by the navigation.xml, always return the same URI given by this config.
http://mydomain/topic/id
Is anyone familiar with this?, Is this possible to do? Is any different way to do something like this? I've tried some different things which make me closer to my goal, but this is the most closer I could...
Thanks.
A better and cleaner way is to zend routes with hostname (eg. sub domains) take a look at following
http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.hostname
this method is more easy and SEO friendly too.

Categories