variables in zend framework bootstrap - zend-framework

I have $view variables in two function in bootstrap file they don't work at the same time unless i comment out one of them, i need to use both function please help
protected function _initNavigation()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
// $view = $layout->getView();
// $navigation = new Zend_Navigation($this->getOption('navigation'));
// $view->navigation($navigation);
}
protected function _initjQuery(){
$view = new Zend_View();
$view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
}

In one function you're using the View object from the layout resource, and in the other you're creating a new View object. If you change your second function to work like the first you don't need to create a new View or inject it into the view renderer.
I'd suggest changing your code to this:
protected function _initNavigation()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$navigation = new Zend_Navigation($this->getOption('navigation'));
$view->navigation($navigation);
}
protected function _initjQuery()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
}

Related

How to Pass value from controller to view in zend framework2

i am beginner to zend.I dont no how to pass vale from controller to update by table using ZfcUser in zend framework2.Here is my code
in UserController.php
public function doneAction()
{
$user = "4";
$planname="checking";
$billamount="$89";
$post=array("planname"=>$planname,"billamount"=>$billamount);
$service = $this->getUserService();
$service->done($user,$post);
return new ViewModel();
}
And in ZfcUser/Serivce/User.php [For storing the value in DB]
public function done($user, array $post)
{
$data=array('planname'=>$post['planname'],'billamount'=>$post['billamount']);
$where = $user->getAdapter()->quoteInto('user_id = 4');
$user->update($data, $where);
return true;
}
Thanks
You can pass values to your view from the controller when creating a new ViewModel instance like so:-
$view = new ViewModel(array(
'user' => $user,
));
return new ViewModel();
Alternatively you can set them against the instance:-
$view = new ViewModel();
$view->user = $user;
return $view;

Zend Framework: How to make view from bootstrap.php

For example i have echo $this->escape($this->test); in index.phtml and in controller $this->view->test = 'test message';, but i want to do this from bootstrap, becouse i want to show Form in every page (controller).
protected function _initView()
{
$this->view = new Zend_View();
$this->view->test = 'test message';
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($this->view);
}
But I would recommend doing this in a controller plugin, not during the bootstrap:
<?php
class My_Controller_Plugin_AddSomethingToViewInAllControllerActions extends Zend_Controller_Plugin_Abstract
{
public function preDispatch()
{
$viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer');
$viewRenderer->initView();
$view = $viewRenderer->view;
$view->test = 'test message';
}
}
sorry i made it
$view = new Zend_View;
$view->setBasePath(APPLICATION_PATH . "/views");
$view->arr = 'message';
echo $view->render('test.php');

Zend: ACL logic in View helpers

Background information:
I'm in my admin module, and I created a view helper in modules/admin/views/helpers/AdminPanel.php. I have a layout plugin that forces my view to use the layout in admin/views/layouts/default.phtml.
I'm trying to access my ACL object to determine whether or not the user has resources in the context of a view helper, and then determine whether to return the admin panel html by parsing a configs/admin-nav.xml or not return anything at all.
I'm calling it in my admin layout like so:
<?php echo $this->AdminPanel(); ?>
And the class code which is blank, which I need to access the acl object in:
class My_View_Helper_AdminPanel extends Zend_View_Helper_Abstract {
public function AdminPanel() {}
}
I tried this:
$acl = Zend_Controller_Action_HelperBroker::getStaticHelper('acl');
But this probably isn't what I'm looking for as it forces the default module's views/layouts/default.phtml to load and errors occur.
Here's my global bootstrap file:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
private $_acl = null;
private $_auth = null;
protected function _initDoctype() {
$this->bootstrap('view');
$view = $this->getResource('view');
$view->setEncoding('UTF-8');
$view->doctype('HTML4_STRICT');
}
protected function _initAutoload() {
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('KG_');
$resourceLoader = new Zend_Loader_Autoloader_Resource(
array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
'resourceTypes' => array(
'form' => array(
'path' => 'forms/',
'namespace' => 'Form_'
),
'model' => array(
'path' => 'models/',
'namespace' => 'Model_'
)
)
));
return $autoloader;
}
protected function _initAclAuth() {
$this->_acl = new Model_Acl;
$this->_auth = Zend_Auth::getInstance();
}
protected function _initNav() {
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$config = new Zend_Config_Xml( APPLICATION_PATH . '/configs/nav.xml', 'mainNav');
$navigation = new Zend_Navigation( $config );
$fc = Zend_Controller_Front::getInstance();
$fc->registerPlugin( new KG_Controller_Plugin_Acl( $this->_acl, $this->_auth ) );
$role = $this->_auth->getStorage()->read()->role;
if ( !$role ) {
$role = 'guest';
}
$view->navigation( $navigation )->setAcl( $this->_acl)->setRole( $role );
}
protected function _initEncoding() {
$fc = Zend_Controller_Front::getInstance();
$response = new Zend_Controller_Response_Http;
$response->setHeader('Content-Type','text/html;charset=utf-8', true);
$fc->setResponse($response);
}
}
Your KG_Controller_Plugin_Acl plugin should be taking care of the access logic, not your view. If the user doesn't have access to the resource, you should error out or redirect the user to somewhere else.
The layout should be set within the controller. Preferably in the init() method with:
$this->_helper->layout->setLayout();
It looks like you followed the same or a similar tutorial as I did for Zend_Acl. I'm posting my plugin for reference, which includes the logic to handle access control from within the plugin:
class App_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
protected $_auth = null;
protected $_acl = null;
public function __construct(Zend_Auth $auth, Zend_Acl $acl)
{
$this->_auth = $auth;
$this->_acl = $acl;
}
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
if ($this->_auth->hasIdentity()) {
$identity = $this->_auth->getIdentity();
$role = $identity->acl_role;
} else {
$role = 'guest';
}
// Mapping to determine which Resource the current
// request refers to (really simple for this example!)
$resource = $request->controller;
$privilege = $request->action;
if (!$this->_acl->has($resource)) {
$resource = null;
}
// ACL Access Check
if (!$this->_acl->isAllowed($role, $resource, $privilege)) {
if ($this->_auth->hasIdentity()) {
// authenticated, denied access, forward to /error/permissions
$request->setModuleName('default');
$request->setControllerName('error');
$request->setActionName('permissions');
} else {
// not authenticated, forward to login form
$request->setModuleName('default');
$request->setControllerName('auth');
$request->setActionName('login');
}
}
}
}

Problem With View Helpers

I wrote few custom view helpers but I have a little trouble using them. If I add the helper path in controller action like this:
public function fooAction()
{
$this->view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
Then I can use the views from that path without a problem. But when I add the path in the bootstrap file like this:
protected function _initView()
{
$this->view = new Zend_View();
$this->view->doctype('XHTML1_STRICT');
$this->view->headScript()->appendFile($this->view->baseUrl()
. '/js/jquery-ui/jquery.js');
$this->view->headMeta()->appendHttpEquiv('Content-Type',
'text/html; charset=UTF-8');
$this->view->headMeta()->appendHttpEquiv('Content-Style-Type',
'text/css');
$this->view->headMeta()->appendHttpEquiv('Content-Language', 'sk');
$this->view->headLink()->appendStylesheet($this->view->baseUrl()
. '/css/reset.css');
$this->view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
Then the view helpers don't work. Why is that? It's too troublesome to add the path in every controller action. Here is an example of how my custom view helpers look:
class My_View_Helper_FooBar
{
public function fooBar() {
return 'hello world';
}
}
I use them like this in views:
<?php echo $this->fooBar(); ?>
Should I post my whole bootstrap file?
UPDATE:
Added complete bootstrap file just in case:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initFrontController()
{
$this->frontController = Zend_Controller_Front::getInstance();
$this->frontController->addModuleDirectory(APPLICATION_PATH
. '/modules');
Zend_Controller_Action_HelperBroker::addPath(
'My/Controller/Action/Helper',
'My_Controller_Action_Helper'
);
$this->frontController->registerPlugin(new My_Controller_Plugin_Auth());
$this->frontController->setBaseUrl('/');
}
protected function _initView()
{
$this->view = new Zend_View();
$this->view->doctype('XHTML1_STRICT');
$this->view->headScript()->appendFile($this->view->baseUrl()
. '/js/jquery-ui/jquery.js');
$this->view->headMeta()->appendHttpEquiv('Content-Type',
'text/html; charset=UTF-8');
$this->view->headMeta()->appendHttpEquiv('Content-Style-Type',
'text/css');
$this->view->headMeta()->appendHttpEquiv('Content-Language', 'sk');
$this->view->headLink()->appendStylesheet($this->view->baseUrl()
. '/css/reset.css');
$this->view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
protected function _initDb()
{
$this->configuration = new Zend_Config_Ini(APPLICATION_PATH
. '/configs/application.ini',
APPLICATION_ENVIRONMENT);
$this->dbAdapter = Zend_Db::factory($this->configuration->database);
Zend_Db_Table_Abstract::setDefaultAdapter($this->dbAdapter);
$stmt = new Zend_Db_Statement_Pdo($this->dbAdapter,
"SET NAMES 'utf8'");
$stmt->execute();
}
protected function _initAuth()
{
$this->auth = Zend_Auth::getInstance();
}
protected function _initCache()
{
$frontend= array('lifetime' => 7200,
'automatic_serialization' => true);
$backend= array('cache_dir' => 'cache');
$this->cache = Zend_Cache::factory('core',
'File',
$frontend,
$backend);
}
public function _initTranslate()
{
$this->translate = new Zend_Translate('Array',
BASE_PATH . '/languages/Slovak.php',
'sk_SK');
$this->translate->setLocale('sk_SK');
}
protected function _initRegistry()
{
$this->registry = Zend_Registry::getInstance();
$this->registry->configuration = $this->configuration;
$this->registry->dbAdapter = $this->dbAdapter;
$this->registry->auth = $this->auth;
$this->registry->cache = $this->cache;
$this->registry->Zend_Translate = $this->translate;
}
protected function _initUnset()
{
unset($this->frontController,
$this->view,
$this->configuration,
$this->dbAdapter,
$this->auth,
$this->cache,
$this->translate,
$this->registry);
}
protected function _initGetRidOfMagicQuotes()
{
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
}
public function run()
{
$frontController = Zend_Controller_Front::getInstance();
$frontController->dispatch();
}
}
Solved. I just needed to add these lines at the end of _initView() method:
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($this->view);
I in my _initView() have something like this:
protected function _initView() {
$view = new Zend_View();
#some view initialization ...
$view->addHelperPath(APPLICATION_PATH . '/views/helpers', 'My_View_Helper');
return $view;
}
Then in a view I can execute:
<?php echo $this->fooBar(); ?>
Without APPLICATION_PATH it does not work in my case.
Just a thought: are you sure that the view that you are creating in your bootstrap ($this->view = new Zend_View();) is the same as '$this' in your view file?
I think you would need to change your initView code to the following:
protected function _initView()
{
$view = new Zend_View();
$view->doctype('XHTML1_STRICT');
$view->headScript()->appendFile($this->view->baseUrl()
. '/js/jquery-ui/jquery.js');
$view->headMeta()->appendHttpEquiv('Content-Type',
'text/html; charset=UTF-8');
$view->headMeta()->appendHttpEquiv('Content-Style-Type',
'text/css');
$view->headMeta()->appendHttpEquiv('Content-Language', 'sk');
$view->headLink()->appendStylesheet($this->view->baseUrl()
. '/css/reset.css');
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
return $view;
}
If you have some View related settings in your config.ini file, you might want to change your code a little bit:
protected function _initMyView()
{
$view = $this->bootstrap('view')->getResource('view');
...
instead of:
protected function _initView()
{
$view = new Zend_View();
....
You might consider adding another init function just for your view helpers:
protected function _initViewHelpers()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
This way the built in view setup is not overridden.
If you add only $this->view->addHelperPath('My/View/Helper', 'My_View_Helper');
in your bootstrap use this format:
class Zend_View_Helper_FooBar extends Zend_View_Helper_Abstract {
public function fooBar() {
return 'hello world';
}
}

Zend Form addFilter StripTags not stripping tags

I need a little help clearing something up with Zend_Form and adding filters to an element. Now I was under the impression that when you add a filter to the form that, when the form is posted that filter was executed as part of dispatch in the controller.
However when testing my form to my horror the filter StripTags doesn't seem to be running and I am getting the data with the HTML tags in the data.
My Form element looks like this.
$address1 = new Zend_Form_Element_Textarea('address1');
$address1->addFilter('StripTags')
->addFilter('StringTrim')
->setAttrib('cols', 30)
->setAttrib('rows', 5)
->removeDecorator('DtDdWrapper')
->removeDecorator('label')
->removeDecorator('HtmlTag')
However if I put in the text area the some data with html tags in it and then check the form is valid using
$formData = $this->_request->getPost();
if($form->isValid($formData){
...
The data comes back with the tags in it. It only removed when I pass the data through the strip_tags() function.
I suppose my question is should the StipTags filter if so why isn't it? What am I missing here.
You didn't post code on how you're accessing the data after calling isValid. IIRC the filters will only take effect if you access the data via $form->getValue('someElement') or something along those lines.
Sorry, i know i'm late but in case any one faced the same problem,
I have faced this problem today and i found few ways to solve this problem:
first my code is:
This is the form class
class Application_Form_UserForm extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setMethod('POST');
$fname = new Zend_Form_Element_Text('fname');
$fname->setLabel('First Name: ');
$fname->setAttribs(Array(
'placeholder'=>'Example: Eslam',
'class'=>'form-control'
));
$fname->setRequired();
$fname->addValidator('StringLength', false, Array(4,20));
$fname->addFilter('StringTrim');
$fname->addFilter('StripTags');
$fname->removeDecorator('DtDdWrapper');
$fname->removeDecorator('label');
$fname->removeDecorator('HtmlTag');
$lname = new Zend_Form_Element_Text('lname');
$lname->setLabel('Last Name: ');
$lname->setAttribs(Array(
'placeholder'=>'Example: Khoga',
'class'=>'form-control'
));
$lname->setRequired();
$lname->addValidator('StringLength', false, Array(4,20));
$lname->addFilter('StringTrim');
$lname->addFilter('StripTags');
$lname->removeDecorator('DtDdWrapper');
$lname->removeDecorator('label');
$lname->removeDecorator('HtmlTag');
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email: ');
$email->setAttribs(Array(
'placeholder'=>'Example#Example.com',
'class'=>'form-control'
));
$email->setRequired();
$email->addValidator('StringLength', false, Array(5,250));
$email->addFilter('StringTrim');
$email->addFilter('StripTags');
$email->removeDecorator('DtDdWrapper');
$email->removeDecorator('label');
$email->removeDecorator('HtmlTag');
$gender = new Zend_Form_Element_Select('gender');
$gender->setRequired();
$gender->addMultiOption('male','Male')->
addMultiOption('female','Female')->
addMultiOption('none','Prefer not to mention');
$gender->setAttrib('class', 'form-control');
$track_obj = new Application_Model_Track();
$allTracks = $track_obj->listAll();
$track = new Zend_Form_element_Select('track');
foreach($allTracks as $key=>$value)
{
$track->addMultiOption($value['id'], $value['name']);
}
$submit= new Zend_Form_Element_Submit('submit');
$submit->setAttribs(array('class'=>'btn btn-success'));
$reset= new Zend_Form_Element_Submit('reset');
$reset->setAttribs(array('class'=>'btn btn-danger'));
$this->addElements(array(
$fname,
$lname,
$email,
$gender,
$track,
$submit,
$reset
));
}
}
This is controller class
class UserController extends Zend_Controller_Action{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function listAction()
{
// action body
$user_model = new Application_Model_User();
$this->view->users = $user_model->listUsers();
$track_form = new Application_Form_Track();
$this->view->track_form = $track_form;
$track_model = new Application_Model_Track();
$request = $this->getRequest();
if($request->isPost())
{
if($track_form->isValid($request->getPost())){
$track_model-> addTrack($request->getParams());
$this->redirect('/user/add');
}
}
}
public function detailsAction()
{
// action body
$user_model = new Application_Model_User();
$us_id = $this->_request->getParam("uid");
$user = $user_model->userDetails($us_id);
$trackModel = new Application_Model_Track();
$track = $trackModel->getTrackName($user[0]['track']);
$user[0]['track'] = $track[0]['name'];
$this->view->user = $user[0];
}
public function deleteAction()
{
// action body
$user_model = new Application_Model_User();
$us_id = $this->_request->getParam("uid");
$user_model->deleteUser($us_id);
$this->redirect("/user/list");
}
public function addAction()
{
// action body
$form = new Application_Form_UserForm();
$request = $this->getRequest();
if($request->isPost()){
if($form->isValid($request->getPost())){
/*echo "<pre>";
print_r($form);
echo "</pre>";
exit;*/
$userData['fname'] = $form->getValue('fname');
$userData['lname'] = $form->getValue('lname');
$userData['email'] = $form->getValue('email');
$userData['gender'] = $form->getValue('gender');
$userData['track'] = $form->getValue('track');
$user_model = new Application_Model_User();
$user_model-> addNewUser($userData);
$this->redirect('/user/list');
}
}
$this->view->user_form = $form;
}
public function editAction()
{
// action body
$form = new Application_Form_UserForm();
$user_model = new Application_Model_User ();
$id = $this->_request->getParam('uid');
$user_data = $user_model-> userDetails($id)[0];
$form->populate($user_data);
$this->view->userName = $user_data['fname']." ".$user_data['lname'];
$this->view->user_form = $form;
$request = $this->getRequest();
if($request->isPost()){
if($form->isValid($request->getPost())){
$userData['fname'] = $form->getValue('fname');
$userData['lname'] = $form->getValue('lname');
$userData['email'] = $form->getValue('email');
$userData['gender'] = $form->getValue('gender');
$userData['track'] = $form->getValue('track');
$user_model-> updateUser($id, $userData);
$this->redirect('/user/list');
}
}
}
}
First Solution:
i used filter on Form elements in the form class,
but i retrieved data from $form object in the controller,
as i found that method
addFilter()
doesn't change in the $_POST array values, so i have retrieved the data from $form object and then passed it as array to Model.
Second Solution:
i have tried to apply the filter on the values in the controller, not in the form by creating object from filter class and apply needed filter
Third Solution:
is to use method
addValidator()
with regex which affects on $_POST values.