Passing url parameters to Zend_Navigation using an XML-file - php

I am using Zend Framework 1.10.8.
I want to create a breadcrumb section in my layout.phtml. There are some links in my menu that have dynamic url parameters like http://mydomain.com/editor/edit/id/42
I try to figure out how to pass id=XXX to Zend_Navigation, while XXX comes from the database and is different in every request.
One solution I found so far is adding a property e.g. params_id to my xml declaration:
in configs/navigation.xml
<pages>
<editor>
<label>Editor</label>
<controller>editor</controller>
<action>edit</action>
<params_id>id</params_id>
<route>default</route>
</editor>
</pages>
and in the controller looping through the pages and dynamically adding my parameter id = 42 (while 42 would be retrieved from the request object in the final version)
$pages = $this->view->navigation()->getContainer()->findAllBy('params_id','id');
foreach ($pages as &$page) {
$page->setParams(array(
'id' => 42,
'something_else' => 667
));
}
As adding dynamic url parameters seems such a basic requirement for Zend_Navigation I am quite sure that my solution is too complicate, too expensive and there must be a much simplier solution "out of the box".

It is very simple. Just write in your XML
<pages>
<editor>
<label>Editor</label>
<controller>editor</controller>
<action>edit</action>
<params>
<id>42</id>
<someting_else>667</something_else>
</params>
<route>default</route>
</editor>
</pages>
Here is example to do it dynamically based on database data
First define Navigation loading plugin. Name the file Navigation.php and place it in application/plugins/ directory. Here's an example of such plugin:
class Plugin_Navigation extends Zend_Controller_Plugin_Abstract
{
function preDispatch(Zend_Controller_Request_Abstract $request)
{
$view = Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view;
//load initial navigation from XML
$config = new Zend_Config_Xml(APPLICATION_PATH . '/configs/navigation.xml','nav');
$container = new Zend_Navigation($config);
//get root page
$rootPage = $container->findOneBy('sth', 'value');
//get database data
$data = Model_Sth::getData();
foreach ($data as $row) {
$rootPage->addPage(new Zend_Navigation_Page_Mvc(array(
'module' => 'default',
'controller' => 'examplecontroller',
'action' => 'exampleaction',
'route' => 'exampleroute',
'label' => $row['some_field'],
'params' => array(
'param1' => $row['param1'],
'param2' => $row['param1']
)
)));
}
//pass container to view
$view->navigation($container);
}
}
Then in you Bootstrap init this plugin
protected function _initNavigation() {
Zend_Controller_Front::getInstance()->registerPlugin(new Plugin_Navigation());
}

An update: I finally ended up throwing away the xml file. What I do now:
I wrote a plugin (see Daimon's approach)
in this plugin I configure my navigation structure as an array, the
dynamic parameters are retrieved from Zend_Request
then I init the navigation using this array

Related

Zend Framework 2 custom style for each user

I am building an application for companies which sends anonymous-links to customers for filling out a questionnaire. The company should be able to change the colors and the logo of the questionnaire to reflect the affiliation to the company's CI.
My idea was to make a folder for every company (in my case, represented as doctrine entity Client) and load the layout's style.css and logo.png etc. dynamically from this folder.
The question: how do I implement this? How can I change a variable in the layout file from the controller? Or do I have to place the whole layout inside the view.phtml file for the ViewModel?
Thanks in advance!
If I had to have several layouts depending on some condition.
I would make the layouts for every company, set them in module.config.php
'view_manager' => array(
'template_path_stack' => array(
'module' => __DIR__ . '/../view/',
),
'template_map' => array(
'layout/company1' => __DIR__ . '/../view/layout/company1.phtml',
'layout/company2' => __DIR__ . '/../view/layout/company2.phtml',
)
),
Then in gloabal.php or in the same module.config.php would add some options:
'companies_layouts' => array(
'IDofComapny1' => 'layout/company1',
'IDofComapny2' => 'layout/company2',
)
And finally in the controller would do something like this:
public function indexAction()
{
$sm = $this->getServiceLocator();
// Getting company identifier
$companyId = $this->params()->fromRoute( 'companyId' );
// do something
...
$this->layout( $sm->get('Config')['companies_layouts'][$comanyId] );
return new ViewModel();
}
If you just need to set css depending on some conditions.
You can just do this in the view file:
switch( true ){
case some condition:
$css = 'file1.css';
break;
case some condition:
$css = 'file2.css';
break;
}
$this->headLink()->appendStylesheet( $css );
And in the layout file you should have next line:
<head>
...
<?= $this->headLink() ?>
...
</head>
You need to set style.css and logo file path according to company name in you action and then you can access this vairable in you layout also as same as you access in view file.
And set you css with headLink() function. and assign logo file in layout header.
You don't need to place layout code in view file.
Write below code on you controller. you can also access style variable in you layout.
return new ViewModel(array( 'style' => $style ,'logo' => $logo));

Yii php: Displaying a widget in a Tab

i've been using Yii framework for some time now, and i've been really having a good time especially with these widgets that makes the development easier. I'm using Yii bootsrap for my extensions..but i'm having a little trouble understanding how each widget works.
My question is how do i display the widget say a TbDetailView inside a tab?
i basically want to display contents in tab forms..however some of them are in table forms...some are in lists, detailviews etc.
I have this widget :
$this->widget('bootstrap.widgets.TbDetailView',array(
'data'=>$model,
'attributes'=>$attributes1,
));
that i want to put inside a tab
$this->widget('bootstrap.widgets.TbWizard', array(
'tabs' => $tabs,
'type' => 'tabs', // 'tabs' or 'pills'
'options' => array(
'onTabShow' => 'js:function(tab, navigation, index) {
var $total = navigation.find("li").length;
var $current = index+1;
var $percent = ($current/$total) * 100;
$("#wizard-bar > .bar").css({width:$percent+"%"});
}',
),
and my $tabs array is declared like this :
$tabs = array('studydetails' =>
array(
'id'=>'f1study-create-studydetails',
'label' => 'Study Details',
'content' =>//what do i put here?),
...
...);
when i store the widget inside a variable like a $table = $this->widget('boots....);
and use the $table variable for the 'content' parameter i get an error message like:
Object of class TbDetailView could not be converted to string
I don't quite seem to understand how this works...i need help..Thanks :)
You can use a renderPartial() directly in your content, like this:
'content'=>$this->renderPartial('_tabpage1', [] ,true),
Now yii will try to render a file called '_tabpage1.php' which should be in the same folder as the view rendering the wizard. You must return what renderPartial generates instead of rendering it directly, thus set the 3rd parameter to true.
The third parameter that the widget() function takes is used to capture output into a variable like you are trying to do.
from the docs:
public mixed widget(string $className, array $properties=array ( ), boolean $captureOutput=false)
$this->widget('class', array(options), true)
Right now you are capturing the object itself in the variable trying to echo out an object. Echo only works for things that can be cast to a string.

What is a minimal, complete example of pagination in Kohana 3.2?

I found much information about pagination in Kohana 3.2 but most of it is scattered across forum comments and blog posts with no single complete source to refer to.
(note: I intended to self answer this question)
This is what worked for me:
Download the pagination module from https://github.com/kloopko/kohana-pagination (pagination was removed from Kohana 3.2, so this is an adapted module).
Install the module in modules/pagination.
Add the module in bootstrap.php:
Kohana::modules(array(
// ... other modules ...
'pagination' => MODPATH.'pagination'
));
Copy the configuration file from modules/pagination/config/pagination.php to application/config/pagination.php.
Add the following actions to your controller:
public function action_index() {
// Go to first page by default
$this->request->redirect('yourcontroller/page/?page=1');
}
public function action_page() {
$orm = orm::factory('your_orm');
$pagination = Pagination::factory(array(
'total_items' => $orm->count_all(),
'items_per_page' => 20,
)
);
// Pass controller and action names explicitly to $pagination object
$pagination->route_params(array('controller' => $this->request->controller(), 'action' => $this->request->action()));
// Get data
$data = $orm->offset($pagination->offset)->limit($pagination->items_per_page)->find_all()->as_array();
// Pass data and validation object to view
echo View::factory('yourview/page', array('data' => $data, 'pagination' => $pagination));
}
Create yourview/page as follows:
<?php
foreach($data as $item) {
// ...put code to list items here
}
// Show links
echo $pagination;
Modify application/config/pagination.php according to your needs. I had to change the 'view' parameter to 'pagination/floating' which displays ellipses (...) when the list of pages is too large, unlike the default 'pagination/basic' which lists all pages regardless of length.
Pagination wasn't originally working/supported in Kohana 3.2. Luckily, somebody has updated the module and you can get the code at https://github.com/kloopko/kohana-pagination

ZF_FORM: How to add some view template for form element?

I created element in form object:
function createElement()
{
$template = new Zend_Form_Element_Hidden('field');
$template->addDecorator('ViewScript', array('placement' => 'prepend', 'viewModule' => 'admin', 'viewScript' => 'values.phtml'))
$this->addElement($template);
}
function setViewTemplate($values)
{
$view = new Zend_View();
$view->setScriptPath(APPLICATION_PATH . '/scripts/');
$view->assign('values', $values);
$this->getElement('field')->setView($view);
}
But in the view script 'values.phtml' I cannot get access to values like $this->values.
What I'm doing wrong here?
I know that it would be good to add own decorator, but it is interesting to use zends' decorators.
From the Zend Framework Documentation: Standard Form Decorators Shipped With Zend Framework Section
Zend_Form_Decorator_ViewScript
Additionally, all options passed to
the decorator via setOptions() that
are not used internally (such as
placement, separator, etc.) are passed
to the view script as view variables.
function setViewTemplate($values)
{
$this->getElement('field')
->getDecorator('ViewScript')
->setOptions('values', $values);
}
you can reslove it with using attribs
$template->setAttrib('key', 'value');
and in template
<?php echo $this->element->getAttrib('key'); ?>

Append param to current URL with view helper in Zend

In my layout-script I wish to create a link, appending [?|&]lang=en to the current url, using the url view helper. So, I want this to happen:
http://localhost/user/edit/1 => http://localhost/user/edit/1?lang=en
http://localhost/index?page=2 => http://localhost/index?page=2&lang=en
I have tried the solution suggested Zend Framework: Append query strings to current page url, accessing the router directly, but that does work.
My layout-script contains:
English
If the default route is used, it will append /lang/en, but when another route is used, nothing is appended at all.
So, is there any way to do this with in Zend without me having to parse the url?
Edit
Sorry for my faulty explanation. No, I haven't made a custom router. I have just added other routes. My bad. One route that doesn't work is:
$Routes = array(
'user' => array(
'route' => 'admin/user/:mode/:id',
'defaults' => array('controller' => 'admin', 'action' => 'user', 'mode'=>'', 'id' => 0)
)
);
foreach( $Routes as $k=>$v ) {
$route = new Zend_Controller_Router_Route($v['route'], $v['defaults']);
$router->addRoute($k, $route);
}
Upd:
You must add wildcard to your route or define 'lang' parameter explicitly.
'admin/user/:mode/:id/*'
Additionally, according to your comment, you can do something like this:
class controllerplugin extends Zend_Controller_Plugin_Abstract
{
function routeShutdown($request)
{
if($request->getParam('lang', false) {
//store lang
Zend_Controller_Front::getInstance()->getRouter()->setGlobalParam('lang', NULL); //check if this will remove lang from wildcard parameters, have no working zf installation here to check.
}
}
}

Categories