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');
Related
I am trying to make a stand alone Zend Form with a custom form element. I need use custom view helper to create this element. How do I register a custom view helper path without an application.ini file?
set_include_path(
implode(PATH_SEPARATOR, array(
get_include_path(),
PATH_TO_ZF_LIBRARY
)));
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace( 'My' );
$form = new Zend_Form;
... create and add zend form elements here
//display form
echo $form->render(new Zend_View());
Also, will the custom Zend_Form_Element know to look for the custom helper in the new path? According to the docs all I have to do is create public $helper var with the class name of the view helper. But I can't figure out if that will work with a custom view helper.
class My_Form_Element_Ssn extends Zend_Form_Element_Xhtml
{
public $helper = 'ssnElement';
public function setValue()
{
}
public function getValue()
{
return '12345';
}
}
class My_View_Helper_SsnElement
extends Zend_View_Helper_FormElement
{
public function ssnElement( $name, $value = null, $attribs = null )
{
return 'SSN';
}
}
I thank you in advance for your assistance.
Try:
$view = new Zend_View();
$view->addHelperPath('/path/to/My/View/Helper', 'My_View_Helper');
echo $form->render($view);
I am trying to redirect the user to a registered page once they have registered but its not doing so..
<?php
class RegisterController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$form = new Application_Form_Register();
$form->submit->setLabel('Register');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$first_name = $form->getValue('first_name');
$surname = $form->getValue('surname');
$email = $form->getValue('email');
$username = $form->getValue('username');
$password = $form->getValue('password');
$is_admin = $form->getValue('is_admin');
$age = $form->getValue('age');
$gender = $form->getValue('gender');
$uni = $form->getValue('uni');
$register = new Application_Model_DbTable_Users();
$register->addUser($first_name, $surname, $email, $username, $password, $is_admin, $age, $gender, $uni);
} else {
$form->populate($formData);
}
$route = array('controller'=>'Register', 'action'=>'registered');
$this->_helper->redirector->gotoRoute($route);
}
}
public function registeredAction()
{
// action body
}
}
This is what I have
Thanks
In the controller you can to the following:
$this->_redirect('/controller/action');
I usually don't use gotoRoute() therefore I am not sure if this is the cause of your problem, but your controller-name should be all lowercased, i.e. Register should be register or maybe gotoRouteAndExit() will solve your problem (just picked it up from a quick glance at the API)
You could try an alternative: For routing between actions/controllers I find the following most convenient:
$this->_helper->redirector('registered');
Which will redirect you to registeredAction in the same controller. If you want to go to an action in a different controller, just add the controller as 2nd argument like this:
$this->_helper->redirector('registered', 'register');
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");
}
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';
}
}
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.