Symfony : How to create Multiple RadioBoxes using the form Builder - php

I'm working on a new project where i was asked to create this type of form :
I have created an entity with a json_array attribute that stores this form
configuration.
example :
{
"DescenteCde" : 0 // checked radiobutton is "Aucun"
"WebShopPC" : 1 // checked radiobutton is "Faible"
}
I want to know the easiest way to generate this type of form using the symfony form builder.

I found a solution for my problem. Actually, Symfony framework provides us with A Collection Type that takes a array as a parameter and then we specify the different options and values/
$ImpactApplicationFormBuilder->add('***Configuration***',CollectionType::class, array(
'entry_type' => ChoiceType::class,
'entry_options' => array(
'choices' => array(
'Aucun' => 0,
'Faible' => 1,
'Moyen' => 2,
'Fort'=> 3
),
'multiple' => false,
"expanded" => true ,
),
));
Configuration attibute is of type array so in the form the different keys of your array will be rendered with the given options you provided.
Your result will look like this :
Hope this help anybody with the same problem

Related

categoryChoiceTree in prestashop module configuration page

I'm developing a prestashop module and I'm trying to show a category tree in my backoffice configuration page.
I'm trying to follow this instructions below but I don't know exactly where to add this code.
It should be inside main module's php? or inside a separate .php file and call it from the main one (don't know how to do it either).
As much time I'm spending trying to figure out, how to implement the code in the link above, the more I think I'm losing my time.
I see that "use" files, and this JS, " /admin-dev/themes/new-theme/js/components/form/choice-tree.js " are not in any prestashop folders.
Well, you should invest some time and learn Symfony since this is what you need to build backend modules for Prestashop 1.7.
As a pointer, you need to create a form class extending the CommonAbstractType, add a build form method. e.g. :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->context = Context::getContext();
$parents = [
['id_category' => 2, 'name' => 'Home', 'children' => $this->getSubCategories(1, true, 2)]
];
$builder->add('category', CategoryChoiceTreeType::class, [
'choices_tree' => $parents,
'choice_value' => 'id_category',
'choice_children' => 'children',
'choice_label' => 'name',
'disabled_values' => $disabledCategories,
'label' => 'Choose a category'
])
then add methods for retrieving the data to populate the form fields.
Then use this class in your controller and display the form:
$form = $this->createForm(YourFormForm::class);
Also add a processForm to process data.
As mentioned, this is not a copy/paste situation you need to understand the Symfony workflow.
The only way that I found to "paint" the categorytree in my configuration page is adding this code to the inputs form array:
Can anyone tell me how to retrieve users selection data to my database?
It does not work as any other form field.
array(
'type' => 'categories',
'label' => $this->l('Destination Category'),
'desc' => $this->l('Select ONE Category'),
'name' => 'CATEGORY_CATEGORY_TO',
'tree' => [
// 'selected_categories' => [],
'disabled_categories' => null,
'use_search' => false,
'use_checkbox' => false,
'id' => 'id_category_tree',
],
'required' => true
),
Well, it is SOLVED!!!! Finally it was very simple, but you must get the correct info for you particular case.
#Robertino's answer might be the best implementation, I don't know, but it became impossible to solve for me,
I uses this code below, and called $categoryTree from the form input. This input must be type=> categories_select
Thanks for your time, and for the help of another post from this forum.
$root = Category::getRootCategory();
//Generating the tree
$tree = new HelperTreeCategories('categories_1'); //The string in param is the ID used by the generated tree
$tree->setUseCheckBox(false)
->setAttribute('is_category_filter', $root->id)
->setRootCategory($root->id)
->setSelectedCategories(array((int)Configuration::get('CATEGORY_1'))) //if you wanted to be pre-carged
->setInputName('CATEGORY_1'); //Set the name of input. The option "name" of $fields_form doesn't seem to work with "categories_select" type
$categoryTree = $tree->render();
And the Form:
array(
'type' => 'categories_select',
'label' => $this->l('Category'),
'desc' => $this->l('Select Category '),
'name' => 'CATEGORY_1', //No ho podem treure si no, no passa la variable al configuration
'category_tree' => $categoryTree, //This is the category_tree called in form.tpl
'required' => true

Symfony Sonata project: How to add multiple input texts to block?

I would like to add a collection of input text with same name (i.e. name="blabla[]") filed to admin block with add/delete buttons.
I'm using collection form field type but can't see add/delete buttons
public function buildEditForm(FormMapper $formMapper, BlockInterface $block)
{
$formMapper->add('settings', 'sonata_type_immutable_array', array(
'keys' => array(
array('title', 'collection',
array('type' => 'text' ,
'required' => true,
'allow_add' => true,
'data' => array('First' => 'One')
)
)
)
));
}
I get below result without add/delete buttons!
Any idea how to get it working ?
I think you should use sonata_type_collection or sonata_type_native_collection instead of collection.
Here is an extract of the field doc :
14.1.7. SONATA_TYPE_NATIVE_COLLECTION (PREVIOUSLY COLLECTION)
This bundle handle the native Symfony collection form type by adding:
an add button if you set the allow_add option to true. a delete button
if you set the allow_delete option to true.

Symfony2- get data of auto populated drop down

I'm having two dropdowns which are not dependent on any entity. When I select the value of first one an ajax function is called to populate the second one which is done perfectly. But, the form after submission, always returns
type_name: ERROR: This value is not valid
My form looks like:
->add('type', 'choice', array(
'empty_value' => "Select",
'choices' => array(
1 => 'One',
2 => 'Two'
)
))
->add('type_name', 'choice', array(
'empty_value' => "Select",
'choices' => array(
),
))
This is because Symfony needs to know the choices beforehand in order to validate them correctly. Currently you are indicating that no choices are valid for your dropdown type_name as you are passing an empty array as choices.
Please check this answer for a detailed guide on how to implement dynamic choices and choice validation: https://stackoverflow.com/a/13374841/606104

Displaying index instead of "__name__label__ *"

Using sonata admin Bundle And I have A form to Define the A "Question" model, I have an attribute "choices" which is a collection :
->add('choices', 'collection',
array('allow_add' => true,'allow_delete' => true, 'block_name' => false,
'delete_empty' => true, 'label' => 'choices'))
When I add a choice The label wrote in his top is "_name__label__*", I need to change it to the choice index, anyone found a solution for this ? thank you

Access custom error messages for InArray validator when using Zend_Form_Element_Select

I'm using Zend Framework 1.62 (becuase we are deploying the finished product to a Red Hat instance, which doesn't have a hgih enough PHP version to support > ZF1.62).
When creating a Form using Zend Form, I add a select element, add some multi options.
I use the Zend Form as an in-object validation layer, passing an objects values through it and using the isValid method to determine if all the values fall within normal parameters.
Zend_Form_Element_Select works exactly as expected, showing invalid if any other value is input other than one of the multi select options I added.
The problem comes when I want to display the form at some point, I cant edit the error message created by the pre registered 'InArray' validator added automatically by ZF. I know I can disable this behaviour, but it works great apart from the error messages. I've tryed the following:
$this->getElement('country')->getValidator('InArray')->setMessage('The country is not in the approved lists of countries');
// Doesn't work at all.
$this->getElement('country')->setErrorMessage('The country is not in the approved lists of countries');
// Causes a conflict elswhere in the application and doesnt allow granular control of error messages.
Anyone have any ideas?
Ben
I usually set validators as per my example below:
$this->addElement('text', 'employee_email', array(
'filters' => array('StringTrim'),
'validators' => array(
array('Db_NoRecordExists', false, array(
'employees',
'employee_email',
'messages' => array(Zend_Validate_Db_Abstract::ERROR_RECORD_FOUND => 'A user with email address %value% already exists')
))
),
'label' => 'Email address',
'required' => true,
));
The validators array in the element options can take a validator name (string) or an array.
When an array is passed, the first value is the name, and the third is an array of options for the validator. You can specify a key messages with custom messages for your element in this array of options.
If your using Zend_Form_Element_Select (or any of the Multi subclasses), on validation the InArray validator will only be automatically added if there is not one present.
You can set a validator as so:
$options = array(...);
$this->addElement('select', 'agree', array(
'validators' => array(
array('InArray', true, array(
'messages' => array(
Zend_Validate_InArray::NOT_IN_ARRAY => 'Custom message here',
),
'haystack' => array_keys($options),
)),
'multiOptions' => $options,
));
and then your validator will be used instead of the automatically attached one.
$el = $this->addElement($name, $label, $require, 'select');
$validator = new Zend_Validate_InArray(array_keys(AZend_Geo::getStatesList()));
$validator->setMessage('Invalid US State.');
$el
->setMultiOptions(AZend_Geo::getStatesList())
->setRegisterInArrayValidator(false)
->addValidator($validator)
->addFilter(new Zend_Filter_StringToUpper())
->addFilter(new T3LeadBody_Filter_SetNull())
->setDescription('US State. 2 char.');

Categories