Translate zend framework 1 form labels and error message - zend-framework

I have a web site which is in English and Arabic. I converted the text into Arabic but the form labels and error message is not converting. I am using gettext adapter and how do i convert this labels. I am using Zend_Form and creating object of this form and passign this to view.
Bootstrap file
protected function _initTranslate() {
$translate = new Zend_Translate('gettext', APPLICATION_PATH . "/lang/", null, array('scan' => Zend_Translate::LOCALE_DIRECTORY));
$registry = Zend_Registry::getInstance();
$registry->set('Zend_Translate', $translate);
//Zend_Form::setDefaultTranslator($translate);
$translate->setLocale('ar');
}
public function _initRoutes() {
$this->bootstrap('FrontController');
$this->_frontController = $this->getResource('FrontController');
$router = $this->_frontController->getRouter();
$langRoute = new Zend_Controller_Router_Route(
':lang', array(
'lang' => 'ar',
'module' => 'default',
'controller' => 'index',
'action' => 'index'
), array(
'lang' => 'en|ar'
)
);
$defaultRoute = new Zend_Controller_Router_Route(
':controller/:action', array(
'module' => 'default',
'controller' => 'index',
'action' => 'index'
)
);
$defaultRoute = $langRoute->chain($defaultRoute);
$router->addRoute('langRoute', $langRoute);
$router->addRoute('defaultRoute', $defaultRoute);
}
protected function _initLanguage() {
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new My_Controller_Plugin_Language());
}
Form
class Application_Form_Contactus extends Zend_Form {
public function init() {
// Set the method for the display form to POST
$this->setMethod('post');
$this->addElement('text', 'name', array('label' => 'Name', 'class' => 'inputbox',
'filters' => array('StringTrim'),
'required' => true));
// Add an email element
$this->addElement('text', 'email', array('label' => 'Email', 'class' => 'inputbox',
'required' => true, 'filters' => array('StringTrim'), 'validators' => array('EmailAddress')));
$this->addElement('submit', 'submit', array(
'required' => false,
'label' => 'Send',
'value' => 'save',
'class' => 'submit-but',
'attribs' => array('type' => 'submit'),
));
}
}
Controller
$form = new Application_Form_Contactus();
$form->setAction($this->view->getSiteUrl() . 'Contactus');
$translate = Zend_Registry::get('Zend_Translate');
$form->element->setTranslator($translate);
$this->view->form = $form;
view
echo $this->form;

Try to attach to the Zend_Form object as a global translator. This will also translate validation error messages :
Zend_Form::setDefaultTranslator($translate);
Or you can do this :
Zend_Validate_Abstract::setDefaultTranslator($translator);
Please see zend form i18n

Try to set default translator.
Zend_Form::setDefaultTranslator($translate);
One more alternate way could be:
$form = new Application_Form_Contactus();
$translate = Zend_Registry::get('Zend_Translate');
foreach ($form->getElements() as $key => $element) {
$element->setTranslator($translate);
}

Related

Prestashop HelperFrom/List - messy layout

I'm new to prestashop and I worked the whole day on creating a back office interface that allows the user to write, edit, and delete articles. It is sort of a blog. I used Prestashop's Helpers (Form and List) and everything works great. I also added a new tab in the back office to access this tool.
The problem is that the layout is messy and doesn't look like the other forms and listing pages. The layout is really not sexy. Maybe I should look at some css file, or add any function in my controller ? You'll find the source code of the latter here (I can't insert images, not enough reputation --'):
<?php
class Article extends ObjectModel
{
/** #var string Name */
public $id_article;
public $titre;
public $contenu;
public $url_photo;
/**
* #see ObjectModel::$definition
*/
public static $definition = array(
'table' => 'article',
'primary' => 'id_article',
'fields' => array(
'titre' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true,
'class' => 'lg'
),
'contenu' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true
),
'url_photo' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => false,
),
),
);
}
class AdminBlogController extends AdminController{
public function initContent(){
parent::initContent();
}
public function __construct(){
$this->table = 'article';
$this->className = 'Article';
$this->lang = false;
// Building the list of records stored within the "article" table
$this->fields_list = array(
'id_article' => array(
'title' => 'ID',
'align' => 'center',
'width' => 25
),
'titre' => array(
'title' => 'Titre',
'width' => 'auto'
),
'contenu' => array(
'title' => 'Contenu',
'width' => 'auto'
)
);
// This adds a multiple deletion button
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?')
)
);
parent::__construct();
}
// This method generates the list of results
public function renderList(){
// Adds an Edit button for each result
$this->addRowAction('edit');
// Adds a Delete button for each result
$this->addRowAction('delete');
return parent::renderList();
}
// This method generates the Add/Edit form
public function renderForm(){
// Building the Add/Edit form
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => 'Article'
),
'input' => array(
array(
'type' => 'text',
'label' => 'Titre',
'name' => 'titre',
'class' => 'lg',
'required' => true,
//'desc' => 'Nom de l\'article',
),
array(
'type' => 'textarea',
'label' => 'Contenu',
'name' => 'contenu',
'class' => 'lg',
'required' => true,
'autoload_rte' => true,
//'desc' => 'Contenu de l\'article',
),
array(
'type' => 'file',
'label' => 'Photo',
'name' => 'url_photo',
'class' => 'lg',
'required' => true,
//'desc' => 'Contenu de l\'article',
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
return parent::renderForm();
}
}
?>
Thank you.
I just needed to set $this->bootstrap = true

I cannot instantiate a model in zend framwork 1.12

I am trying to build a Registration and login process how ever I am new to Zend I can't instantiate a model class:
application/models/users.php
class Users extends Zend_Db_Table_Abstract
{
protected $_name = 'users';
}
in my bootstrap I performed autoloading this way
application/bootstrap
protected function _initAutoload()
{
//Add autoloader empty namespace
require_once 'Zend/Loader/Autoloader.php';
$autoLoader = Zend_Loader_Autoloader::getInstance();
$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 it so that it can be stored by the bootstrap
return $autoLoader;
}
on my controller I have this
public function indexAction()
{
$frmuser = new Application_Form_Contact;
$users = new Application_Model_Users;
$this->view->form = $frmuser;
// action body
}
I have a form that works fine in application\forms\contact.php
class Application_Form_Contact extends Zend_Form
{
public function init()
{
$this->setMethod('post');
/* Form Elements & Other Definitions Here ... */
$this->addElement('text', 'username',array('filters' => array('StringTrim'), 'required' => true,'label' => 'Enter a Username:', 'validators' => array
(array('StringLength', false, array(2, 50)))));
$this->addElement('text', 'firstname',array('filters' => array('StringTrim'), 'required' => true,'label' => 'Enter your Firstname:', 'validators' =>
array(array('StringLength', false, array(2, 50)))));
$this->addElement('text', lastname, array('filters' => array('StringTrim'), 'required' => true,'label' => 'Enter your Lastname:', 'validators' => array
(array('StringLength', false, array(2, 50)))));
$this->addElement('text', 'email', array('filters' => array('StringTrim'), 'required' => true,'label' => 'Enter your Email:', 'validators' => array
('EmailAddress', array
('StringLength', false, array(2, 50)))));
$this->addElement('text', 'emailagain', array('filters' => array('StringTrim'), 'required' => true,'label' => 'Confirm your Email:', 'validators' =>
array('EmailAddress', array('StringLength', false, array(2, 50)))));
$this->addElement('password', 'password', array('filters' => array('StringTrim'), 'required' => true,'label' => 'Enter a password:', 'validators' =>
array(array('StringLength', false, array(2, 50)))));
$this->addElement('password', 'passwordagain', array('filters' => array('StringTrim'), 'required' => true,'label' => 'Confirm your password:',
'validators'=> array(array('StringLength', false, array(2, 50)))));
$this->addElement('submit', 'contact');
$this->view->form = $form;
}
}
if I comment out the $users = new Application_Model_Users the form displays well but if uncommented,
pointing to the url in the internet explorer browser will display the code like this:
class Users extends Zend_Db_Table_Abstract { protected $_name = 'users'; }
The easiest way to define a model is use zftool.
or you can make changes in your application like this to make your model work:
application\models\DbTable\users.php
class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract {
protected $_name = 'users';
}
In your Controller now you are able to access it like this:
$users = new Application_Model_DbTable_Users();
Further details are provided in zend framework documentation:
Read it carefully to find out perfect way to implement it:
Zend Framework 1.12 Documentation

How to create multiple form submit buttons with alternate routes in ZF2

In ZF2, how do you create multiple submit buttons that each lead to different routes? In the Forms and actions chaper of the ZF2 tutorial, a form is created with a single submit button with the label “Go” that processes the input data and returns to the index page (route). Where do we put the pertinent scripts if we wanted four buttons:
Save action: saves user input, route: return to current page
Save and Close action: saves user input, route: return to index (Album)
Clear action: no action, route: return to current page
Close action: no action, route: return to index (Album)
I assume the buttons are created like this:
namespace Album\Form;
class AlbumForm extends Form
{
public function __construct($name = null)
{
// ... //
$this->add(array(
'name' => 'savebutton',
'attributes' => array(
'type' => 'submit',
'value' => 'Save',
'id' => 'savebutton',
),
));
$this->add(array(
'name' => 'save_closebutton',
'attributes' => array(
'type' => 'submit',
'value' => 'Save & Close',
'id' => 'save_closebutton',
),
));
$this->add(array(
'name' => 'clearbutton',
'attributes' => array(
'type' => 'submit',
'value' => 'Clear',
'id' => 'clearbutton',
),
));
$this->add(array(
'name' => 'closebutton',
'attributes' => array(
'type' => 'submit',
'value' => 'Close',
'id' => 'closebutton',
),
));
}
}
This is what the edit action looks like with only one submit button:
// module/Album/src/Album/Controller/AlbumController.php:
//...
// Add content to this method:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('album', array(
'action' => 'add'
));
}
$album = $this->getAlbumTable()->getAlbum($id);
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getAlbumTable()->saveAlbum($form->getData());
// Redirect to list of albums
return $this->redirect()->toRoute('album');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
//...
Since pairs of buttons have the same form action and pairs of buttons have the same route, I image we want to add two if statements somewhere here, unless a switch statement is better.
Quick 'n dirty way to do what you need:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('album', array(
'action' => 'add'
));
}
$album = $this->getAlbumTable()->getAlbum($id);
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$input = $form->getData();
if (!empty($input['save_closebutton'])) {
return $this->redirect()->toRoute('album', array(
'controller' => 'AlbumController',
'action' => 'index',
));
}
}
}
return array(
'id' => $id,
'form' => $form,
);
}

Zend Framework: My form wont render

So I have created a form below with Zend Framework which I'm then going to customise. My first issue is that with the csrf hash security I get an application error. However, when I remove them lines all I get is a blanks screen which is only resolved when I remove the CPATCHA protection. Can anyone explain to me why?
My Form:
class Application_Form_Clips extends Zend_Form
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
// Add an email element
$this->addElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
)
));
// Add the comment element
$this->addElement('textarea', 'comment', array(
'label' => 'Please Comment:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add a captcha
$this->addElement('captcha', 'captcha', array(
'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'captcha' => array(
'captcha' => 'Figlet',
'wordLen' => 5,
'timeout' => 300
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Sign Guestbook',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}
My Controller:
class AdminController extends Zend_Controller_Action
{
public function init()
{
// get doctrine and the entity manager
$this->doctrine = Zend_Registry::get('doctrine');
$this->entityManager = $this->doctrine->getEntityManager();
// get the users repository
$this->indexVideos = $this->entityManager->getRepository('\ZC\Entity\Videos');
$this->indexClips = $this->entityManager->getRepository('\ZC\Entity\Clips');
}
public function indexAction()
{
// action body
}
public function clipsAction()
{
// get a form
$form = new Application_Form_Clips();
$this->view->form = $form;
}
public function videosAction()
{
// action body
}
}
My View:
<?php echo $this->form; ?>
Basic error, I hadn't uncommented session.pat in my php.ini

Zend_Auth now only works partial

Okay,
This is completely a weird situation.
When a user logs in, I store some stuff using the following code:
$auth->getStorage()->write($authAdapter->getResultRowObject(array(
'username',
'avatar',
'status',
'role',
'id',
'email'
)));
Then I use the following code in my bootstrap to get access to the variables:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function preDispatch()
{
$this->frontController = Zend_Controller_Front::getInstance();
}
protected function _initBuildBase()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$this->view = $layout->getView();
// Set doctype
$this->view->doctype("XHTML1_TRANSITIONAL");
$this->view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');
}
protected function _initLoader()
{
$adminLoader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'Admin',
'basePath' => APPLICATION_PATH));
$autoLoader = Zend_Loader_Autoloader::getInstance();
$autoLoader->registerNamespace('MyApp_');
$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
'resourceTypes' => array(
'model' => array(
'path' => 'models/',
'namespace' => 'Models_'
),
'service' => array(
'path' => 'services/',
'namespace' => 'Services_'
),
'form' => array(
'path' => 'forms/',
'namespace' => 'Forms_'
),
),
));
return $autoLoader;
return $adminLoader;
}
protected function _initControllerPlugins()
{
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_ApplicationSettings);
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_LayoutLoader);
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_LanguageSelector);
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_Acl);
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_Uploadify);
}
protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH .'/views/helpers');
}
protected function _initRoutes()
{
$router = $this->frontController->getRouter();
$router->addRoute(
'crud',
new Zend_Controller_Router_Route('/:module/:controller/:action/:id', array('module' => 'admin', 'controller' => ':controller', 'action' => ':action', 'id' => ':id'))
);
$router->addRoute(
'pagination',
new Zend_Controller_Router_Route('/:module/:controller/index/:page', array('module' => 'admin', 'controller' => ':controller', 'action' => 'index', 'page' => ':page'))
);
$router->addRoute(
'pageUrl',
new Zend_Controller_Router_Route('/:page/:subpage', array('module' => 'default', 'controller' => 'index', 'action' => 'index', 'page' => ':page', 'subpage' => ':subpage'))
);
}
protected function _initLogin()
{
$this->auth = Zend_Auth::getInstance();
$this->view->user = $this->auth->getIdentity();
}
}
Okay, and now for the weird part:
When I use
if($this->user->role == 'Administrator')
{
In my layout.phtml it works great. But when I use the same code in a index.phtml file which is loaded according to the controller it doesn't work?!
The stranger part is that it used to work perfectly and use it t show different options depending of the user's role.
Where could I look for mistakes in my code? Really lost on places to check on. Probably changed something somewhere, but everything else seems to work fine.
Any tips or directions would be awesome!
The layout and view resource both do use the Zend_Controller_Action_Helper_ViewRenderer(). The layout resource accesses the helper to get the view (readonly). But the view resource accesses the helper and overwrites the view object of the helper.
So in your case the layout got bootstrapted, you did set the variables. Afterwards the view resource is bootstrapted which overwrites the view in the helper.
You always should bootstrap the view before the layout to ensure they both use the same view object.