class Module_PhotoController extends Core_Controller_Action_Standard
{
public function nameAction()
{
$this->view->form = $form = new Modulename_Form_Fromname();
$this->addElement('Text', 'sender', array(
'label' => 'Send to',
'maxlength' => '40',
'filters' => array(
//new Engine_Filter_HtmlSpecialChars(),
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_StringLength(array('max' => '63')),
)
));
}
}
Try this code
$form->addElement('Text', 'sender', array(
'label' => 'Send to',
'maxlength' => '40',
'filters' => array(
//new Engine_Filter_HtmlSpecialChars(),
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_StringLength(array('max' => '63')),
)
));
Proper way to do this is to edit file that's in /application/modules/Modulename/Form/Fromname.php and use addElement to add specific elements to the form. Constructing forms in controllers isn't best SE programming practice.
Related
The Zend quickstart guide:
http://framework.zend.com/manual/2.2/en/modules/zend.form.quick-start.html
Implies that the form factory can attach the filters automatically by adding them to the configuration array, rudimentary testing demonstrates that validation is occurring, but nothing is getting passed back to the view ( formElementErrors or formRow ).
)
Factory Array
$this->form = array(
'hydrator' => 'Zend\Stdlib\Hydrator\ArraySerializable',
'elements' => array(
array(
'spec' => array(
'name' => 'name',
'options' => array(
'label' => 'Your name',
),
'attributes' => array(
'type' => 'text'
),
)
),
array(
'spec' => array(
'type' => 'Zend\Form\Element\Email',
'name' => 'email',
'options' => array(
'label' => 'Your email address',
)
),
),
array(
'spec' => array(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'security',
),
),
array(
'spec' => array(
'name' => 'send',
'attributes' => array(
'type' => 'submit',
'value' => 'Submit',
),
),
),
),
'input_filter' => array(
'name' => array(
'required' => true,
'filters' => array(
array('name' => 'Zend\Filter\StringTrim'),
),
),
'email' => array(
'required' => true,
'filters' => array(
array('name' => 'Zend\Filter\StringTrim'),
),
'validators' => array(
new Validator\EmailAddress(),
),
)
)
);
Controller
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Form\Factory;
use Application\Form\Login;
class LoginController extends AbstractActionController
{
public function indexAction()
{
$factory = new Factory();
$login = new Login();
$form = $factory->createForm($login->form);
if ($this->getRequest()->isPost())
{
$form->setData( $this->getRequest()->getPost() );
/*
if ($form->isValid())
{
die('valid');
}
else
{
die('invalid');
}
*/
}
return(array('form' => $form));
}
public function loginAction()
{
die('login');
}
}
View
<?php
$form = $this -> form;
$form -> prepare();
$form -> setAttribute('method', 'post');
$formLabel = $this -> plugin('formLabel');
echo $this -> form() -> openTag($form);
?>
<div class="form_element">
<?php echo $this -> formRow($form -> get('name'));?>
</div>
<div class="form_element">
<?php echo $this -> formRow($form -> get('email')); ?>
</div>
<?php echo $this->formElement($form -> get('security')); ?>
<?php echo $this->formElement($form -> get('send')); ?>
<?php echo $this->form()->closeTag(); ?>
This is a quick one - I don't tend to use $this->formRow(), but I think you'll have add <?php echo $this->formElementErrors($elementInstance); ?>
into your markup
From http://framework.zend.com/manual/2.2/en/modules/zend.form.quick-start.html
"Validating forms requires three steps. First, the form must have an input filter attached. Second, you must inject the data to validate into the form. Third, you validate the form. If invalid, you can retrieve the error messages, if any."
I had wrongly assumed that the validation would automatically attach the feedback to the form. The code below attaches error messages if required.
Thanks to all SO users that took interest.
if ($form->isValid()) {
$validatedData = $form->getData();
// Do something useful
} else {
$messages = $form->getMessages();
}
I'm trying to build a VERY simple form and want to add the validation in the form itself. No need for million lines of code when adding it in the form just is about 3 lines.
Here are two of my fields:
$this->add(array(
'name' => 'username',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Name*',
'required' => true,
),
'filters' => array(
array('StringTrim')
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'E-Mail*',
'required' => true,
),
'validators' => array(
array('regex', true, array(
'pattern' => '/[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/i',
'messages' => 'Bitte eine gültige E-Mailadresse angeben'))
),
'filters' => array(
array('StringTrim')
),
));
The $form->isValid() ALWAYS returns true. Even if the field is empty. I have another field with a regex-validator, same thing... WTF, Zend?
My controller looks like this:
$form = new UserForm();
$form->setHydrator(new DoctrineEntity($entityManager));
$request = $this->getRequest();
if ($request->isPost()) {
$backenduser = new User();
$form->bind($user);
$form->setData($request->getPost());
if ($form->isValid()) {
....
}
Any ideas?
Validation- and Filtering-Definitions aren't part of the Form itself. See http://framework.zend.com/manual/2.0/en/user-guide/forms-and-actions.html
Try this, pass $_POST data.
if($form->isValid($_POST)) {
// success!
} else {
// failure!
}
I try to validate with the form but I cant get error messages.
//this is my code:
$form = new TestForm();
$form->setInputFilter(new TestFilter());
$data = array('id'=>'','email'=>'myemail#myemail.com');
$form->setData($data);
if($form->isValid()){
echo 'ok';
} else {
echo 'not ok <br/>';
$messagesForm = $form->getMessages();
$filter=$form->getInputFilter();
$messagesFilter=$filter->getMessages();
var_dump($messagesForm);
var_dump($messagesFilter);
}
/////////////////
Output
not ok
//messagesForm
array
empty
//MessagesFilter
array
'id' =>
array
'isEmpty' => string 'Value is required and can't be empty' (length=36)
_
How is possible? The filter is ok, but I can't get error messages from the form
Could be a bug or I made something wrong?
FULL code:
TestFilter:
_
<?php
namespace mvc\filter;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
class TestFilter extends InputFilter
{
public function __construct()
{
$factory = new InputFactory();
$this->add($factory->createInput(array('name'=>'id','required'=>true)));
$this->add($factory->createInput(array('name'=>'email','required'=>true)));
}
}
?>
_
TestForm
_
namespace mvc\form;
use Zend\InputFilter\Factory;
use Zend\Form\Element;
use Zend\Form\Form;
class TestForm extends Form
{
public function prepareElements()
{
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'text',
'label' => 'Your name',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'email',
'label' => 'Your email address',
),
));
}
}
?>
_
I have not worked with ZF2 yet but try to add validators to your elements:
use Zend\Validator;
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'text',
'label' => 'Your name',
),
'validator' => new StringLength(array('max'=>20))
));
}
you must specify 'validators', example of a getInputFilter:
use
Zend\InputFilter\InputFilter,
Zend\InputFilter\Factory as InputFactory,
Zend\InputFilter\InputFilterAwareInterface,
Zend\InputFilter\InputFilterInterface;
class User implements InputFilterAwareInterface
{
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'email',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
You may do it this way by retrieving input filter from your model and then setting it to a form:
...
$form = new ItemForm();
$form->setInputFilter($user->getInputFilter());
$form->setData($params);
if ($form->isValid()) {
...
}
...
First : sorry for my long message.
I'm trying to learn Fuel, but I have some problems with Fieldset class and Orm.
I've create a Model which extends ORM, in order to get an automatic generated form, according to my database.
My Model
class Model_Product extends \Orm\Model
{
protected static $_table_name = 'products';
protected static $_properties = array(
'id' => array(
'data_type' => 'int'
),
'name' => array(
'data_type' => 'varchar',
'label' => 'Name',
'validation' => array(
'required', 'trim', 'max_length'=>array(30), 'min_length'=>array(3)
),
),
'description' => array(
'data_type' => 'varchar',
'label' => 'Description',
'validation' => array(
'max_length' => array(290)
),
'form' => array(
'type' => 'textarea'
),
),
'price' => array(
'data_type' => 'integer',
'label' => 'Price',
'validation' => array(
'required', 'trim', 'valid_string' => array('numeric','dots')
),
),
'pic' => array(
'data_type' => 'varchar',
'label' => 'Path to the pic',
'validation' => array(
'required', 'trim'
),
),
'registered' => array(
'data_type' => 'date',
'label' => 'Registration date',
'validation' => array(
'required', 'trim'
) //'valid_string' => array('numeric','dashes')
),
);
} //end of class Model_Product
Then I create the controller which will validate the form.
My function from the controller
function action_add()
{
$fieldset = Fieldset::forge('add_product')->add_model('Model_Product')->repopulate();
$form = $fieldset->form();
$form->add('submit', '', array('type' => 'button', 'value' => 'Add item', 'class' => 'button-link' ));
$validation = $fieldset->Validation();
if($validation->run() === true)
{
$fields = $fieldset->validated();
//create a new Product, with validated fields
$product = new Model_Product;
$product->name = $fields['name'];
$product->description = $fields['description'];
$product->price = $fields['price'];
$product->pic = $fields['pic'];
$product->registered = $fields['registered'];
try
{
//if the product is successfully inserted in the database
if($product->save())
{
Session::set_flash('success', 'Product successfully added !');
\Response::redirect('products/product_details/'.$product->id);
}
}
catch(Exception $e)
{
Session::set_flash('error', 'Unable to save the product into the database !'.$e->getMessage());
}
}
//If the validation doesn't pass
else
{
Session::set_flash('error', $fieldset->show_errors());
}
$this->template->set('content', $form->build(), false);
} // end of method add()
My first question :
How and where in my function from controller can i add a 'fieldset' tag with a specific class, in order to 'beautify' my auto-generated form ?
Let's say
<fieldset class="add_product">
Second question :
What do I have to do in order to correctly validate de 'price' field, because in MySQL is set as decimal(5,2), but when I'm trying to validate with my actual validation rule, it doesn't pass (it works only with integer values Ex.: 42, but not with decimal Ex.: 42.35). I have tried to change the type from 'integer' to 'double', but it doesn't work .
If you can point to some specific documentation regarding my problems, which I possible didn't read yet, please do feel free.
Gabriel
I can answer the first question To change the automatically generated form you will need to copy fuel/core/config/form.php to the fuel/app/config directory and edit this file to suit your needs.
I have create a form class for editing deleting and add users to a database. If I want to edit a user how can I simply supply the information of the user to the form.
I use a Zend_Db_Table to get the data from the database.
This is the userForm class:
class UsersForm extends Zend_Form
{
public function init ()
{
$username = new Zend_Form_Element_Text('username',array(
'validatrors' => array(
'alpha',
array('stringLength',5,10)
),
'filters' => array(
'StringToLower'
),
'required' => true,
'label' => 'Gebruikersnaam:'
));
$password = new Zend_Form_Element_Password('password', array(
'validators'=> array(
'Alnum',
array('StringLength', array(6,20))
),
'filters' => array('StringTrim'),
'required' => true,
'label' => 'Wachtwoord:'
));
$actif = new Zend_Form_Element_Checkbox('actif', array(
'label' => 'actif'));
$this->addElements(array($username,$password,$actif));
$this->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')),
array('Description',array('placement' => 'prepand')),
'Form'
));
}
}
Thank you,
Ivo Trompert
This is done with:
$form->populate($data);
where $data is an array with your table-row-data where the field names have to match the ones from the form. Zend will do the rest.
one of the 'fetchXXX' or 'find' methods on your extended Db_Table will return a Rowset, calling current() on that will give you a Row, which has a toArray method that will give you the format tharkun's response is asking for.