How to preopulate zend file elements - zend-framework

I have a Zend form like this:
$this->setName('Add Job');
$id = new Zend_Form_Element_Hidden('id');
$id->addFilter('Int');
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Name')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$file = new Zend_Form_Element_File('file');
$file->setLabel('File')
->setRequired(true);
$category = new Zend_Form_Element_Checkbox('category');
$category->setLabel('Express?')
->setRequired(true)
->setCheckedValue('2')
->setUncheckedValue('1');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setAttrib('id', 'submitbutton');
The "add" action is working fine but I'm not working on the "edit" action using this in my controller:
$id = $this->_getParam('id', 0);
if ($id > 0) {
$jobs = new Application_Model_DbTable_Jobs();
$form->populate($jobs->getJob($id));
}
and the form prepopulates just fine except for the file element. In the DB, I've got the filename saved and I'd like to display it in the edit form somehow - is there a standard way of handling this in Zend?
Thanks,
Phil

You cannot prepopulate a file-input-element.
That is not a restriction by Zend_Form. The html input-file-element has no "value" attribute.

i used a trick, to pass the filename to the view, so one can for example show the image next to the upload. In your form type this:
$this->getElement('image')->setAttrib('class', $this->_myParams['data']['image']);
$image->setDecorators(array(
'File',
array('ViewScript', array('viewScript' => '/ditta/_image.phtml', 'placement' => false)))
);/
then in the viewscript use
$image = $this->element->getAttrib('class');//get name of file
$this->element->setAttrib('class', '');//delete class

Related

How to Set value for password filed using Zend Form

This My Edit user form in Zend Frame work
$this->setAttrib('enctype', 'multipart/form-data');
$this->setName('user');
$id = new Zend_Form_Element_Hidden('id');
$id->addFilter('Int');
$fname = new Zend_Form_Element_Text('fname');
$fname->setLabel('Full Name')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email Address')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$add = new Zend_Form_Element_Text('add');
$add->setLabel('Address')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$pass = new Zend_Form_Element_Password('pass');
$pass->setLabel('Password')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$city = new Zend_Form_Element_Text('city');
$city->setLabel('city')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$img = new Zend_Form_Element_File('img');
$img->setLabel('Profile picture')
->setRequired(true);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setAttrib('id', 'submitbutton');
// add element in form
$this->addElements(array($id, $fname, $email, $add, $pass, $city, $img, $submit));
And I am Set the value for form elemets using following code in controller
$form = new Application_Form_User();
$form->submit->setLabel('Save');
$this->view->form = $form;
$id = $this->_getParam('id', 0);
if ($id > 0) {
$user = new Application_Model_DbTable_User();
$info = $user->getUser($id);
//$form->populate($info);
$form->setDefaults($info);
I am used $form->setDefaults($info); methode to set vlaue for form field. This method set value sucessfully for only Text input type but This method can not set value which has input type is password. so, what would i do for set vlaue for to input type is password?
This is my output screen edit.php
Zend does not allow password field to be auto-filled. Html type="password" also prevents the browsers to supports autocomplete. You will have to enter the password manually each time the page is refreshed.
However to disable autocomplete on a field use.
$foo = new Zend_Form_Element_Text('foo', array(
'autocomplete' => 'off',
));
// or...
$form->addElement('text', 'foo', array(
'autocomplete' => 'off',
));
// or...
$element->autocomplete = 'off';
I know this is an old question but I came across it whilst looking for the same answer so I thought I'd post my findings.
There is a setRenderPassword(true) property for password fields in Zend_Form.
$pass = new Zend_Form_Element_Password('pass');
$pass->setLabel('Password')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty')
->setRenderPassword(true);

Create model instance in Form in ZF2 like ZF1?

In ZF1 it is possible to create an instance of a model and also access its properties from any form class.`
class Application_Form_Drydepot extends Zend_Form
{
$model = new Application_Model_DbTable_DrydepotModel();
$List = $model ->formationSelect();
array_unshift($List, array('key' => '', 'value' => '--Please Select--'));
$id = new Zend_Form_Element_Hidden('id');
$id->addFilter('Int')
->setDecorators($this->elementDecoration);
$formation = new Zend_Form_Element_Select('formation_id');
$formation->setLabel('Formation Name')
->setRequired(true)
->setAttrib('id', 'formation')
->setAttrib('class', 'required')
->addValidator('NotEmpty', true)
->setMultiOptions($List)
->setDecorators($this->elementDecoration);
}
In here $model directly possible to call but use it easily but zf2 it is quite difficult. I am not successfull about to do it. In ZF2 how do I do it same operation.
Another ways are like here : the documentation
Programmatic Form Creation
ZF2 Coding close to ZF1
use Zend\Captcha;
use Zend\Form\Element;
use Zend\Form\Form;
$captcha = new Element\Captcha('captcha');
$captcha
->setCaptcha(new Captcha\Dumb())
->setLabel('Please verify you are human');
$form = new Form('my-form');
$form->add($captcha);

Strange behaviour with Zend_Form_Element_Select

I'm having strange behaviours with my Zend Form. The fields to be filled with a "select" button remain empty (NULL) in the database, and the value of one them is put in another field.
Here's my code:
public function init()
{
$this->setName('projet');
$id = new Zend_Form_Element_Text('codeProjet'); //works great
$id->setLabel('Code du Projet');
$nomproj = new Zend_Form_Element_Text('nomProjet'); //is filled with the codeEntreprise value
$nomproj->setLabel('Nom du Projet')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim');
$deb = new Zend_Form_Element_Text('dateDebut'); //works great
$deb->setLabel('Date du début')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim');
$fin = new Zend_Form_Element_Text('dateFin'); //works great
$fin->setLabel('Date de fin')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim');
$montant = new Zend_Form_Element_Text('montantPrevu'); //works great
$montant->setLabel('Montant prévu')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim');
$chef = new Zend_Form_Element_Select('matriculeChef'); //remains empty
$options=array('select'=>'[select]');
$chef->setLabel('Chef de Projet')
->setRequired(true);
$boss = new Application_Model_DbTable_Developpeur();
foreach($boss->fetchAll() as $p)
$options[$p['matricule']]=$p['prenom'].' '.$p['nom'];
var_dump($options);
$chef->addMultioptions($options);
$chef->setValue($selected);
$boite = new Zend_Form_Element_Select('codeEntreprise'); //remains empty
$option=array('select'=>'[select]');
$boite->setLabel('Nom de l\'entreprise');
$entr = new Application_Model_DbTable_Entreprise();
foreach($entr->fetchAll() as $p)
$option[$p['codeEntreprise']]=$p['nom'];
var_dump($option);
$boite->addMultioptions($option);
$envoyer = new Zend_Form_Element_Submit('envoyer');
$envoyer->setAttrib('id', 'boutonenvoyer');
$this->addElements(array($id, $nomproj,$deb,$fin,$montant,$chef,$boite, $envoyer));
}
Do you have any idea why one field is filled with a wrong value, and why some remain empty in the database?
Thanks.
on the following line :
$chef->setValue($selected);
where is $selected coming from?
You should use $form->populate($dataFromDb or $_POSTdata) to fill the values IMO.

Validate a set of fields / group of fields in Zend Form

Is there any good solution for the following requirements:
A form with one field for zip code and default validators like number, length, etc.
After submission, the form is checked against a database.
If the zip code is not unique we have to ask for an city.
Examples:
Case 1: Submited zip code is unique in database. Everything is okay. Process form
Case 2: Submited zip code is not unique. Add a second field for city to the form. Go back to form.
We want to handle this in an generic way (not inside an controller). We need this logic for
a lot of forms. First thought was to add it to isValid() to every form or write a
validator with logic to add fields to the form. Subforms are not possible for us, because we need this for different fields (e.g. name and street).
Currently I'm using isValid method inside my forms for an User Form to verify the password and confirm password field. Also, when the form is displayed in a New Action, there are no modifications, but when displayed in an Edit Action, a new field is added to the form.
I think that is a good option work on the isValid method and add the field when the validation return false, and if you want something more maintainable, you should write your own validatator for that purpose.
Take a look at my code:
class Admin_Form_User extends Zf_Form
{
public function __construct($options = NULL)
{
parent::__construct($options);
$this->setName('user');
$id = new Zend_Form_Element_Hidden('id');
$user = new Zend_Form_Element_Text('user');
$user->setLabel('User:')
->addFilter('stripTags')
->addFilter('StringTrim')
->setAllowEmpty(false)
->setRequired(true);
$passwordChange = new Zend_Form_Element_Radio('changePassword');
$passwordChange->setLabel('Would you like to change the password?')
->addMultiOptions(array(1 => 'Sim', 2 => 'Não'))
->setValue(2)
->setSeparator('');
$password = new Zend_Form_Element_Password('password');
$password->setLabel('Password:')
->addFilter('stripTags')
->addFilter('StringTrim')
->setRequired(true);
$confirm_password = new Zend_Form_Element_Password('confirm_password');
$confirm_password->setLabel('Confirm the password:')
->addFilter('stripTags')
->addFilter('StringTrim')
->addValidator('Identical')
->setRequired(true);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Save');
$this->addElements(array($id,$name,$lastname,$group,$user,$passwordChange,$password,$confirm_password,$submit));
$this->addDisplayGroup(array('password','confirm_password'),'passwordGroup');
$this->submit->setOrder(8);
$this->setDisplayGroupDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'div','id' => 'div-password'))
)
);
$passwordChange->clearDecorators();
}
public function addPasswordOption()
{
$this->changePassword->loadDefaultDecorators();
$this->getDisplayGroup('passwordGroup')
->addDecorators(array(
array('HtmlTag', array('tag' => 'div','id' => 'div-password'))
)
);
$this->password->setRequired(false);
$this->confirm_password->setRequired(false);
}
public function setPasswordRequired($flag = true)
{
$this->password->setRequired($flag);
$this->confirm_password->setRequired($flag);
}
public function isValid($data)
{
$confirm = $this->getElement('confirm_password');
$confirm->getValidator('Identical')->setToken($data['password']);
return parent::isValid($data);
}
}
So, in my controller:
public function newAction()
{
$this->view->title = "New user";
$this->view->headTitle($this->view->title, 'PREPEND');
$form = $this->getForm();
if($this->getRequest()->isPost())
{
$formData = $this->_request->getPost();
if($form->isValid($formData))
{
$Model = $this->getModel();
$id = $Model->insert($formData);
$this->_helper->flashMessenger('The user data has beed updated.');
$this->_helper->redirector('list');
}
}
$this->view->form = $form;
}
public function editAction()
{
$this->view->title = "Edit user";
$this->view->headTitle($this->view->title, 'PREPEND');
$id = $this->getRequest()->getParam('id');
$form = $this->getForm();
// Add yes or no password change option
$form->addPasswordOption();
$Model = $this->getModel();
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
// Change password?
if($formData['changePassword'] == 2) $form->setPasswordRequired(false);
if($form->isValid($formData))
{
$Model->update($formData);
$this->_helper->flashMessenger('The user data has beed updated.');
$this->_helper->redirector('list');
}
}
$data = $Model->getById($id)->toArray();
$form->populate($data);
$this->view->form = $form;
}
You will probably need a Javascript form validator for that. In the submit function perform an AJAX call to check if the zipcode is unique. If not, show an extra city field.
But you still have to perform the validation server side: never trust user input, even if it's validated on the client side.

PHP Zend doesn't display correctly

I am trying to recreate the following blog's tabbed forms for my website.
http://zendguru.wordpress.com/2009/01/15/zend-framework-and-dojo-creating-tabbed-form/
I currently have the form displaying on my page, however instead of tabs it displays the whole form like normal. I know that the form is displaying the subforms as I have commented them out and they disappear. Can someone help me find the path to enlightenment? I believe everything relevant is below. I have included the dojo Base 1.4.0 located
http://www.dojotoolkit.org/downloads
I have a link to the html being created here if that helps as well.
http://shortText.com/tljfsq6l37
I have the following AdminController.php page.
class AdminController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function createeventAction()
{
$this->view->page = 'createEvent';
$this->view->title = "Early Signup Administration";
$this->view->headTitle($this->view->title, 'PREPEND');
$createEventForm = new Form_CreateEvent();
$this->view->form = $createEventForm;
}
}
?>
An CreateEvent.php Form
<?php
class Form_CreateEvent extends Form_Event
{
public function __construct($options = null)
{
parent::__construct($options = null);
$shirt_sizes = array('s' => 'Small', 'm' => 'medium', 'l' => 'large', 'xl' => 'X-Large', 'XX' => 'XX-Large', '3X' => 'XXX-Large');
$this->setDecorators(array(
'FormElements',
array('TabContainer', array(
'id' => 'tabContainer',
'style' => 'width: 600px; height: 500px;',
'dijitParams' => array(
'tabPosition' => 'top'
),
)),
'DijitForm',
));
$this->setName('createEvent');
$idEvent = new Zend_Form_Element_Hidden('idEvent');
$type = parent::setName($this->type);
$name = parent::setName($this->name);
$city = parent::setName($this->city);
$state = parent::setName($this->state);
$location = parent::setName($this->location);
$date = parent::setName($this->date);
$shirtRequired = parent::setName($this->shirtRequired);
$eventImage = parent::setName($this->eventImage);
$eventUrl = parent::setName($this->eventUrl);
//$submit = parent::setName($this->submit);
$shirtSize = new Zend_Form_Element_MultiCheckbox ('shirtSize');
$shirtSize->setLabel('Shirt Size')
->setRequired(false)
->addMultiOptions($shirt_sizes)
->setValue(array('s','m','l','xl'))
->addFilter('StripTags')
->addFilter('StringTrim');
$directorEmail = new Zend_Form_Element_Text('email');
$directorEmail->setLabel('Director\'s Email')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim');
$waiverTitle = new Zend_Form_Element_Text('waiverTitle');
$waiverTitle->setLabel('Waiver Title')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim');
$waiverText = new Zend_Form_Element_Text('waiverText');
$waiverText->setLabel('Waiver Text')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim');
$eventClosedMessage = new Zend_Form_Element_Text('eventClosedMessage');
$eventClosedMessage->setLabel('Event Closed Message')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim');
$logoFlag = new Zend_Form_Element_Radio('logoFlag');
$logoFlag->setLabel('Select Logo Image')
->setRequired(false)
->addMultiOptions(array(
'logo' => 'Logo',
'not_logo' => 'Not Logo'))
->addFilter('StripTags');
/* $this->addElements(array($shirtSize,
$directorEmail,
$waiverTitle,
$waiverText,
$eventClosedMessage,
$logoFlag
)); */
$subForm1 = new Zend_Dojo_Form_SubForm();
$subForm1->setAttribs(array(
'name' => 'textboxtab',
'legend' => 'Text Elements',
'dijitParams' => array(
'title' => 'Text Elements',
),
));
$subForm1->addElements(array($shirtSize,
$directorEmail,
$waiverTitle));
$subForm2 = new Zend_Dojo_Form_SubForm();
$subForm2->setAttribs(array(
'name' => 'toggletab',
'legend' => 'Toggle Elements',
));
$subForm2->addElements(array(
$waiverText,
$eventClosedMessage,
$logoFlag
));
$this->addSubForm($subForm1, 'textboxtab')
->addSubForm($subForm2, 'editortab');
}
}
?>
The following in the header.phtml that is included on that page.
<SCRIPT TYPE="text/javascript" SRC="/dojo/dojo.js"></SCRIPT>
<script type="text/javascript">
dojo.require("dojo.parser");
</script>
and the following on the createEvent.phtml page I am trying to view
<?php echo $this->form ;?>
Difficult to tell exactly what the problem might be without your CSS etc. - but you do seem to have some pretty serious issues in your HTML source, so would try to get them fixed before anything else.
For example, you have a duplicate <html> element inside the <div id="head"> element (including duplicated <head> and <body> elements), and that is bound to lead to somewhat unpredictable behaviour.
Have to say I'm not quite sure how you would have got that kind of output. Are you using layouts? It sort of looks like you may have created the inner <html> element in your view script, and then it's been wrapped in a second one by the layout script. Maybe just check you're definitely only creating the html, head, body elements in one place and see where that gets you to start with...