Zend Framework: My form wont render - zend-framework

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

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

Translate zend framework 1 form labels and error message

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);
}

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_Form not valid but no error messages

i have a strange Problem with one of my Zend_Forms: isValid() correctly states that my form isn't valid but i do not get any error messages. How could that happen?
Heres the code, nothing special here. $data is an array of post data. The problem occurs when no file is sended.
$form = $this->getForm('Foto');
if(!$form->isValid($data)) {
var_dump( $form->getErrors() ); die;
return false;
}
getForm() initializes the form if not allready done. The form itself is pretty straight forward.
class Media_Forms_Foto extends Zend_Form
{
/**
* Initializer function. Setup forms fields.
*/
public function init()
{
$this->setName('add Image');
$this->setAction('media/gallery/addImage');
$this->addElement('Hidden', 'gallery', array(
'filters' => array(),
'validators' => array('Digits'),
'required' => false,
'label' => '',
));
$this->addElement('File', 'foto', array(
'required' => true,
'destination' => ROOT_PATH .'public/upload/tmp/',
'label' => 'Foto',
'validators' => array(
new Zend_Validate_File_IsImage(array(
'image/jpeg', 'image/gif', 'image/png'
))
),
'maxFileSize' => 2097152,
));
$this->addElement('Submit', 'add', array(
'required' => false,
'ignore' => true,
'label' => 'add Foto',
));
$this->setAttrib('enctype', 'multipart/form-data');
}
}
Output:
array(3) {
["gallery"]=>
array(0) {
}
["foto"]=>
array(0) {
}
["add"]=>
array(0) {
}
}
Are you using the jquery form plugin by any chance? if so, try using the iframe mode to upload files:
var options = {
url: '/test/upload',
success: function(response) {
},
beforeSubmit: disableSubmitButtons,
iframe: true,
dataType : 'json'
};
$('#testForm').ajaxForm(options);