laravel 4 form helpers - including additional attributes - forms

Within Laravel 4 I can create a select box in a form with this helper:
Form::select('name', $data)
where $data represents an array of the select options.
However I want to now add an extra attribute of 'Required' to help with form validation on the client side.
I can do this if I use normal php and markup but I'd like to use the laravel helper if I can.
I've tried adding:
Form::select('name', $data, array('required'=>'required'))
This doesn't appear to add anything to the final mark up. I've tried the following but this doesn't work either:
Form::select('name', $data, array('required'))
Is there an easy way of doing this or accept that I should revert to another method without a helper

If you check the FormBuilder class the select field is declared as
public function select($name, $list = array(), $selected = null, $options = array())
So what you are passing is the third parameter which should be the default selected option from the list.
In order to achieve what you need you have to pass the array of $options as the fourth parameter (if you don't have default selection just leave the third parameter null)
Form::select('name', $data, null, array('required'=>'required'))

Related

In Symfony2 project how can I pass an array as value to submit method

In Symfony2 project how can I pass an array as value to submit method ?
My form need 7 parameters, so when I do it with a handleRequest() way it's work fine by filling the form manually, but if I try with an array and submit() it fails.
Note that the array I pass to the submit method is not in the same order, has no token and has 8 values instead of 7.
And of course I don't use the handleRequest method.
But the key of the $data[0] array are the same that the name of the entity's properties
$addForm = $this->createForm('ns_add', $entity);
$addForm->submit($data[0]);
EDIT : Almost good, with :
$addForm = $this->container->get('form.factory')->createNamed(null, 'ns_add', $entity);
All the parameters are passed to the form, I can see it on the Symfony profiler (the tool under every Symfony application), but I still have one error : The CSRF token is invalid. Please try to resubmit the form.
Since I have all 7 my field filled + 1 the submit field I only have the "_token" field missed, so I try to add it to my $data[0] but it don't appear on the var_dump of my array, but if I add a key other than "_token", it appear (and cause error : no extra field allowed or kind).
So I was thinking is because of the token of my first form. In fact the real form is a 7 inputs text form, but I created a export button that extract the configuration of the entity I export.
And then, when I upload the file via the form that contain the configuration, I already have the TOKEN. This is a view of the FORM SECTION on the profiler :
ns_zippedfile [ns_zippedfile]
file [file]
ok [submit]
_token [hidden]
(no name) [ns_add]
name [text]
adapter [choice]
dbname [text]
host [text]
port [text]
username [text]
password [password]
submit [submit]
So maybe I need to find a way to not merge the forms, this no name section confuse me.
Try
$addForm = $this->container->get('form.factory')->createNamed(null, 'ns_add', $entity);
instead of
$addForm = $this->createForm('ns_add', $entity);
Don't care about fields order.
You can disable CSRF protection if it don't need:
$addForm = $this->container->get('form.factory')->createNamed(null, 'ns_add', $entity, ['csrf_protection' => false]);
I solved my problem,
$addForm = $this->container->get('form.factory')->createNamed(null, 'ns_add', $entity);
was good, but instead of null parameter I better put the same value that the parameter 2, ns_add . Works fine.
$addForm = $this->container->get('form.factory')->createNamed('ns_add', 'ns_add', $entity);
N.B.: Don't forget to generate the token and save it in the array of data for the field :
$data[0]['_token'] = $this
->get('form.csrf_provider')
->generateCsrfToken('ns_add')
;
N.B.2:ns_add, here is the name of my form, view getName() method of your EntityType class form.

ZF2 refresh input filter after dynamicly adding elements to form

I have a form that triggers on event in __construct method to load some items from another modules . So far so good , a field set is loaded from the other module and added to the form and in the request->getPost() I have the data for the elements inside the fieldset , but the $form->getData() doesn't have the data for the fieldset.
I am calling $form->getInputFilter() before adding this fieldsets to the form and it seems that calling the $form->getInputFilter() dosn't creates the filters for the newly added elements . so how can i create inputfilters for the dynamic events without recreating the hole filters again ?
Or should i just delay calling $form->getInputFilter() untill all of the elemnts have been added to the form ?
I also added some elements to the form later what was ignored by the input filter.
My solution is most likely not exactly the best one, but as you haven't received any other answers yet, here's what I did:
I added
use Zend\InputFilter\Factory as InputFactory;
in the class where I'm validating the form data and then used
$factory = new InputFactory();
$form->getInputFilter()->add($factory->createInput(array(
'name' => 'title_str',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
#Afterdark017 that works and also i think it is possible to reset the filters.
protected function resetFilters(){
$this->filter = null;
$this->hasAddedInputFilterDefaults = false;
}
but i have not tested this yet.

Passing variables to a viewScript Decorator

I have tried adding a partial to my form using the Zend Form's viewScript decorator, however i seem unable to pass along variables to the partial. Here's my code:
In the controller i add the form:
$form = new Content_Form_ContentForm(array("categories" => $sortedCategories));
$form->submit_button->setLabel("Add content");
$this->view->form = $form;
Then inside the form i add the viewscript:
public function setCategories($categories) {
$this->setDecorators(array(array('ViewScript', array(
'viewScript' => 'partials/dtreePartial.phtml',
'List'=>"{$categories}",
))));
}
I have tried printing the options for the view script by using print_r($this->getDecorator('ViewScript')->getOptions()); wich results in Array ( [viewScript] => partials/dtreePartial.phtml [List] => Array )
However when i run it all, the script returns an error about the List not existing.
I have the feeling i am missing something but i am unsure as to what it is. Any advice or solutions will be appreciated! :)
The problem is with this line:
'List'=>"{$categories}",
Because you put the variable inside quotes, it gets cast to a string. In PHP, when you cast an array to a string, the result is always the word Array.
Simply change to:
'List'=> $categories,
and it should work as you expect.

Populate values to checkbox while editing in zend framework

I am trying to populate the values into check box. I want check box to be checked when there is value stored in database.
This is my code in form:
$form ['test_1'] = new Zend_Form_Element_Checkbox('test_1');
$form['test_1']->setLabel('test1')->setCheckedValue('1');
$form ['test_2'] = new Zend_Form_Element_Checkbox('test_2');
$form['test_2']->setLabel('test2')->setCheckedValue('2');
If there is value 1 in database i want first check box to be checked and if its 2 then 2nd checkbox needs to be checked.
What do i need to do in the controller.
Could anyone please help me on this issue.
The easiest way would be to fetch the values from the database as an array that maps to the form input elements, e.g. return a row like
array('test_1' => 'value of checkbox', 'test_2' => 'value of checkbox');
You could then simply call $form->populate($values) and let do Zend_Form do the setting, e.g. in your controller do
public function showFormAction()
{
$form = $this->getHelper('forms')->get('MyForm');
$data = $this->getHelper('dbGateway')->get('SomeTable');
$form->populate($data->getFormData());
$this->view->form = $form;
}
Note: the helpers above do not exist. They are just to illustrate how you could approach this. Keep in mind that you want thin controllers and fat models, so you should not create the form inside the controller, nor put any queries in there.

Zend Avoid submit button value in GET parameters in url

I have a form, created with Zend_Form, with method = GET used for searching records with elements as below:
[form]
user name [input type="text" name="uname"]
[input type="submit" value="Search" name="search"]
[/form]
After form is submitted all the GET parameters along with submit button value are appearing in the url.
http://mysite.com/users/search?uname=abc&search=Search
How to avoid submit button value appearing in the url? is custom routing the solution ?
When you create your element, you can simply remove the name attribute that was automatically set at creation
$submit = new Zend_Form_Element_Submit('search')->setAttrib('name', '');
Or inside a Zend_Form
// Input element
$submit = $this->createElement('submit', 'search')->setAttrib('name', '');
// Or Button element
$submit = $this->createElement('button', 'search')->setAttribs(array
(
'name' => '', 'type' => 'submit',
);
When a form gets submitted, all of its elements with their names and values become a part of a GET / POST - query.
So, if you don't want an element to appear in your GET - query, all you need to do is to create this element without a name. That's probably not the best approach, but since we're talking about the 'submit' element, I guess it doesn't matter that much.
Looking at Zend_View_Helper_FormSubmit helper, you can see that it's creating the 'submit' element and setting its name. So, the possible solution would be to create your own view helper and use it for rendering the 'submit' element instead of the default helper.
You can set a custom helper with
$element->setAttribs( array('helper' => 'My_Helper_FormSubmit') );
Then build your own form element class and remove the name attribute from the element with preg_replace. The beauty of it is, it will not interfere with the other decorators.
So the something like this:
class My_Button extends Zend_Form_Element_Submit
{
public function render()
{
return preg_replace('/(<input.*?)( name="[^"]*")([^>]*>)/', "$1$3", parent::render(), 1);
}
}
You can remove name attribute for submit button in javascript.
jQuery example:
$('input[name="submit"]').removeAttr('name');
In the controller that represents the form's action, redirect to another (or the same controller) only including the relevant params.
Pseudocode:
$params = $this->getRequest()->getParams();
if isset($params['search'])
unset($params['search']);
return $this->_helper->Redirector->setGotoSimple('thisAction', null, null, $params);
handle form here
This is basically the same idea as Post/Redirect/Get except that you want to modify the request (by unsetting a parameter) in between the different stages, instead of doing something persistent (the images on that Wiki-page shows inserting data into a database).
If I were you, I would leave it in. IMO it's not worth an extra request to the webserver.