Zend Framework : Setting up default values for part of the multicheckbox element options not possible - zend-framework

I'm writing this question cause I have difficulties setting up default values for a _MultiCheckbox element of a Zend Framework 1.9.3.
I create Zend_Form_Element_MultiCheckbox with multiple options like this:
$multiCheckbox = new Zend_Form_Element_MultiCheckbox( 'elId',
array ( 'disableLoadDefaultDecorators' =>true ) );
$multiCheckbox ->setName( 'elId' )
->setLabel('elId')
->setRequired( false )
->setAttrib('class', 'inputtext')
->setDecorators( array( 'ViewHelper' ) )
->setMultiOptions( $options );
where the $options array is an associative array 'key' => 'value'. The field is displayed just fine and I can get all the checked values for that element.
When returning to that page I need to restore from the DB the whole list of options again and mark the checked ones. I have tried to do it like that:
$multiCheckbox ->setValue( $defaults );
where $default is array, containing elements of type 'checked_option_field_id' => true(eg. array( '1222' => true, '1443' => true ) ). That action checks ALL the checkboxes and not only the once I need and I have passed to the setValue() method.
I have tried to pass just an array containing elements of type 'checked_option_field_id', (eg. array( '1222', '1443' ) )but that also doesn't work - NONE of the checkboxes is checked.
I have used the form setDefaults() method with those two kinds of arrays, but the results are same - as this method uses again setValue() for each element.
MultiCheckbox element is rendered like that ( result when try to set checked value for only one option ):
<label for="elId-1222"><input type="checkbox" name="elId[]" id="elId-1222" value="1222" checked="checked" class="inputtext">BoRoom </label><br />
<label for="elId-1443"><input type="checkbox" name="elId[]" id="elId-1443" value="1443" checked="checked" class="inputtext">BoRoom Eng2 </label><br/>
That element populates the checked option values in the elId[] array. That is the element name.
setDefaults() form method gets all form elements by name and commit their default values by calling setDefault() form method and after that setValue() element method. So my multicheckbox element has name elId ( it does not get all the element options one by one ) and set default values for all options instead of just the given in the array.
That is how I see it and I can't find solution how to set default values only for some of the options of a multicheckbox element.

Chris is correct that setValue() expects an array of values to be 'checked' (not an array of bool values keyed by your option IDs).
If you are looking for the logic behind the form generation, don't look at the Zend_Form_Element object (or the many extended elements from it), look at the Zend_View_Helper objects. Specifically the Zend_View_Helper_FormRadio object.
When generating the HTML the options array is looped, then the value is checked against the value array - the array passed to setValue(), using in_array().
From Zend_View_Helper_FormRadio line: 150
// is it checked?
$checked = '';
if (in_array($opt_value, $value)) {
$checked = ' checked="checked"';
}
Not sure what that's not working for you, but if you're passing:
$element->setMultiOptions(array('1111' => 'Some Label',
'2222' 'Some Other Label',
'3333', 'Not Selected Label'));
$element->setValue(array('1111','2222');
It should work. Maybe if you could include some code it would be easier to see what's going on?

The setValue() expects a array with those values that need to be checked, in this case for example you need to pass a array with values 1222, 1443 for them to be marked as checked.

You need to serialize the checkbox value before insert in database. To show the database value selected again you have to unserialize the data to show.
The details you can read from following link
http://abser-web-tips.blogspot.com/2010/09/zend-framework-multiple-check-box.html
Thanks

Related

gravity forms Form Entry - display label, not value for checkboxes, select

I've got checkboxes and selects where label is different to its value.
In the DB the value is saved ok, however, when viewing Form Entries (and pre-submit form data) for all the checkboxes and selects the values are displayed not labels. So I end up with not so informative IDs rather than names.
Is there a way to display labels instead of values in the Form Entries screen?
I came across your question while looking to do the same thing. I have a field called Account Type that stores the account type ID as the value. In the entries list I want to show the account type name, not the ID.
Here's the solution:
In your theme's functions.php file add the following filter:
add_filter( 'gform_entries_column_filter', 'modify_entry_view', 10, 5 );
You'll find the documentation for it here: https://docs.gravityforms.com/gform_entries_column_filter/
Then add the function code:
function modify_entry_view( $value, $form_id, $field_id, $entry, $query_string ){
//- Check the field ID to make sure you only change that one
if( $field_id == 14 ){
return 'modified value';
};
return $value;
}
In my case I'm using a custom field that I created called account_type that prepopulates a select menu with choices corresponding to each of the account types in our system. I used the following call to check the field type instead of checking based on field id since the id will change from form to form:
if( RGFormsModel::get_field( $form_id, $field_id )->type == 'account_type' ){
You could do the same thing but use the label property instead of type, like:
if( RGFormsModel::get_field( $form_id, $field_id )->label == 'Field Label' ){
In my case the value saved is a term id from a custom taxonomy I set up called account_type, so I simply use:
return get_term_by( 'id', $value, 'account_type' )->name;
to replace the account id with the account name.
FYI: The process is the same for the entry detail, use the filter documented here: https://docs.gravityforms.com/gform_entry_field_value/

How to generate input select in laravel blade form and customize its options value?

I'm trying to create a laravel form that have an input select generating from array of strings coming from controller.
How can I set values of options manually?
In controller :
public function create()
{
$eventTypes = EventType::all()->lists('title');
return View::make('events.create')->with(compact('eventTypes'));
}
In view (blade) :
{{ Form::label('eventType', 'Type') }}
{{ Form::select('eventType', $eventTypes, null, array('class'=> 'form-control')) }}
And select created as :
<select class="form-control" id="eventType" name="eventType">
<option value="0">Sport Competition</option>
<option value="1">Movie</option>
<option value="2">Concert</option>
</select>
I just want to set values manually.
The value in the options is just the key of the array. The second parameter to the lists() method will let you choose a field to use as the key:
// use the 'id' field values for the array keys
$eventTypes = EventType::lists('title', 'id');
If you want to do something more custom than that, you'll need to manually build your array with the key/value pairs you want.
Edit
As mentioned by #lukasgeiter in the comments, there is no need to call all() first.
EventType::all()->lists() will first generate a Collection of all the EventType objects. It will then call lists() on the Collection object, meaning it will loop through that Collection to build an array with your requested fields.
EventType::lists() will call lists() on the query builder object, which will just select the two requested fields and return those as the array. It will not build any EventType objects (unless you select a field built by a Model accessor).

A set of fields for one property entity in Symfony 2

My Product entity has the following structure:
private $id;
private $title;
/**
* #ManyToOne(targetEntity="Category")
* #JoinColumn(name="cat_id", referencedColumnName="id")
*/
private $category;
Category have nested structure. And each level of nesting is shown in 5 separate fields:
In class form code, I solve it in this way:
$builder
->add('cat_1', 'entity', array(
...
'query_builder' => function() { return someSelectLogic1(); }
))
->add('cat_2', 'entity', array(
...
'query_builder' => function() { return someSelectLogic2(); }
))
->add('cat_3', 'entity', array(
...
'query_builder' => function() { return someSelectLogic3(); }
))
->add('cat_4', 'entity', array(
...
'query_builder' => function() { return someSelectLogic4(); }
))
->add('cat_5', 'entity', array(
...
'query_builder' => function() { return someSelectLogic5(); }
))
Now I need to know which field is filled in the last turn and pass the value of that field in the entity property.
In all that I do not like:
complex logic to determine which field with category was filled at the end
each of these fields is not tied to the entity 'mapped' => false
1) What the right way to organize code of my form?
2) And is there a way to bring these fields into a separate class which will deal with the logic of determining which category was chosen in the end?
I would suggest the following:
1) Create a new custom form field type and put all those entity in there.
This process is not much different from ordinary creation of form type. Just enclose those fields in it's own buildForm() and that should do the trick. Docs.
2) Mark all those entity fields with property "property_path => false".
Clearly you wont be storing these values inside your model.
3) Add two more fields: chosen and lastOne.
Now, this might be tricky: I would either set the chosen to text type (basically, generic type) or would use entity as well. If you go for entity you would need to include all possible answers from all entity fields. As for the lastOne set it to text as it will reflect which field (by name) was selected last.
Either way, those two fields will be invisible. Don't forget to set property_path to false for lastOne field.
4) Finally, add ValueTransformer (docs) which will contain logic to "see" which field was selected last.
Now, I dealt with it only once and don't understand it just quite yet, so your best bet would be trial and error with examples from official docs, unfortunately.
What basically you should do is to, within value-transformer, read the value of field lastOne. This will give you the name of field which was selected last. Then, using that value, read the actual last value selected. Last, set that value (object, if you've went for entity type, or it's ID otherwise) to chosen field.
That should basically do the thing.
As for the JS, I don't know if you're using any framework but I will assume jQuery. You will need to set lastOne field as your selecting items in your form.
$(function(){
$('#myform').find('select').on('change', function(){
var $this = $(this);
$this.closest('form').find('#__ID_OF_YOUR_LASTONE_FIELD').val($this.attr('name'));
});
});
I'm sorry I cannot provide you with code samples for PHP right now. It's a bit late here and will do my best to further update this answer tomorrow.

Entity mapping in a Symfony2 choice field with optgroup

Suppose to have an entity in Symfony2 that has a field bestfriend, which is a User entity selected from a list of User entities that satisfy a complex requirement.
You can render this field in a form by specifying that it is an entity field type, i.e.:
$builder->add('bestfriend', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'property' => 'username',
));
This form field is rendered as a <select>, where each one of the displayed values is in the form:
<option value="user_id">user_username</option>
So, one would render the field by using the <optgroup> tags to highlight such special feature of the friends.
Following this principle, I created a field type, namely FriendType, that creates the array of choices as in this answer, which is rendered as follows:
$builder->add('bestfriend', new FriendType(...));
The FriendType class creates a <select> organized with the same <option>s but organized under <optgroup>s.
Here I come to the problem! When submitting the form, the framework recognize that the user field is not an instance of User, but it is an integer. How can I let Symfony2 understand that the passed int is the id of an entity of type User?
Here follows my solution.
Notice that it is not mentioned in the Symfony2 official docs, but it works! I exploited the fact that the entity field type is child of choice.
Hence, you can just pass the array of choices as a param.
$builder->add('bestfriend', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'choices' => $this->getArrayOfEntities()
));
where the function getArrayOfEntities() is a function that fills the choice list with the friends of my friends, organized by my friends:
private function getArrayOfEntities(){
$repo = $this->em->getRepository('AcmeHelloBundle:User');
$friends = $repo->findAllFriendByComplexCriteria(...);
$list = array();
foreach($friends as $friend){
$name = $friend->getUsername();
if(count($friend->getFriends())>0){
$list[$name] = array();
foreach($friend->getFriends() as $ff){
$list[$name][$ff->getUsername()] = $ff;
}
}
}
return $list;
}
I know the example could be meaningless, but it works...
PS: You need to pass the entity manager to let it working...

Does the symfony form fields initialize to null if not visible

I have few fields on the form like name, description, timestamp.
Now in the form I am only displaying name and description but not timestamp.
public function __construct()
{
$this->setTimestamp(new \DateTime());
}
Now in my database, it is coming as null.
Either doctrine is not executing constructor or those fields are set to null when displayed in form.
Even though I am not displaying them.
You need put the timestamp field in your FormType.
If you don't need to show it, just hide the field and set default value.
Something like that:
$builder->add('timestamp', 'hidden', array(
'data' => new \DateTime(),
));
Don't forget {{form_rest(form)}} at end of the twig template to send all hidden fields.