Doctrine ChoiceType setting a default value on form load - forms

I have created a form on a Symfony CRM using the buildForm() function in a form type file. This form includes a choice drop down consisting of simple "yes" and "no" options which map to 1 and 0 respectively. I need to be able to have "no" as the default as my client more often will select this option over the "yes". After reading the documentation here I figured that the preferred_choices option would suit my needs.
Here is my entry in the buildForm() :
$builder->add('non_rider', ChoiceType::class,
array(
'label' => 'Is Non-Rider',
'required' => true,
'placeholder' => false,
'choices' => array(
'Yes' => 1,
'No' => 0
),
'preferred_choices' => array(0,1),
'label_attr' => array(
'class' => 'control-label'
),
'attr' => array(
'class' => 'form-control required'
)
));
However, this brings out the order as "Yes" then "No" with "Yes" as the default selected option. I was wondering if it reads 0 as null, which means it doesn't register? Is there any way to make "No" the auto-selected option on form load?

You can use the "data" option as mentioned here symfony.com/doc/current/reference/forms/types/choice.html, and show in action here http://stackoverflow.com/a/35772605/2476843
$builder->add('non_rider', ChoiceType::class,
array(
'label' => 'Is Non-Rider',
'required' => true,
'placeholder' => false,
'choices' => array(
'Yes' => 1,
'No' => 0
),
'data' => 0,
'preferred_choices' => array(0,1),
'label_attr' => array(
'class' => 'control-label'
),
'attr' => array(
'class' => 'form-control required'
)
));

Related

Validation error "This value should not be blank" when submitting a form on production website

I'm developing a website using php 7.4, symfony 5.4 and twig. This website is deployed on several servers.
On one of the servers (RedHat), a form cannot be submitted. I get the following error 4 times : "This value should not be blank.".
The messages appear on top of the form and aren't attached to a particular field.
I can't reproduce this error on another server, nor on my development environment...
The problem might comes from a validator but I'm not sure whether it's a symfony or a doctrine error.
The POST data is identical on production server and dev environment :
report_selection[iFrame]: 1
report_selection[dteFrom]: 2023-01-30 07:00
report_selection[dteTo]: 2023-01-31 07:00
report_selection[reportType]: 1
report_selection[size]: 200
report_selection[product]: 1
report_selection[submit]:
I assume that the empty field submit is not a problem since other forms work fine while having the same field empty.
The database structure is the same on all servers.
Here is the form's code :
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$bDisplaySize = $options['bDisplaySize'];
$bDisplayReportType = $options['bDisplayReportType'];
$bDisplayProduct = $options['bDisplayProduct'];
$defaultValue = $options['defaultValue'];
$em = $options['entity_manager'];
list($H, $m) = explode(":", $iShiftStart);
$initialFromDate = (new DateTime())->modify('-'.$H.' hour');
$initialFromDate = $initialFromDate->modify('-1 day');
$initialFromDate->setTime((int)$iShiftStart, (int)$m, 0);
$initialToDate = clone $initialFromDate;
$initialToDate = $initialToDate->modify('+1 day');
$builder->add(
'iFrame',
ChoiceType::class,
array(
'label' => 'master.preselection',
'choices' => [
'master.yesterday' => false,
'master.today' => false,
'master.thisWeek' => false,
'master.lastWeek' => false,
'master.thisMonth' => false,
'master.lastMonth' => false,
'master.memomryDate' => false,
],
'attr' => ['onchange' => 'refreshPreselectedChoices()'],
'choice_attr' => [
'master.yesterday' => [],
'master.today' => ['selected' => 'selected'],
'master.thisWeek' => [],
'master.lastWeek' => [],
'master.thisMonth' => [],
'master.lastMonth' => [],
'master.memomryDate' => ['disabled' => true],
],
)
);
$builder->add(
'dteFrom',
TextType::class,
array(
'label' => 'form.from',
'data' => $initialFromDate->format('Y-m-d H:i'),
'attr' => array(
'style' => 'width:150px;',
'oninput' => 'dteFromToCustom()',
'onchange' => 'dteFromToCustom()',
),
)
);
$builder->add(
'dteTo',
TextType::class,
array(
'label' => 'form.to',
'data' => $initialToDate->format('Y-m-d H:i'),
'attr' => array(
'label' => 'form.to',
'style' => 'width:150px;',
'oninput' => 'dteFromToCustom()',
'onchange' => 'dteFromToCustom()',
),
)
);
if ($bDisplayReportType) {
$builder->add(
'reportType',
ChoiceType::class,
array(
'label' => 'summaryReport.data',
'choices' => array(
'summaryReport.type1' => '1',
'summaryReport.type2' => '2',
),
)
);
}
if ($bDisplaySize) {
$builder->add(
'size',
EntityType::class,
array(
'class' => ProductsSizeSpecs::class,
'choice_label' => 'rSize',
'choice_value' => 'rSize',
'placeholder' => '',
'label' => 'form.size',
'required' => false,
'mapped' => false,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('e')
->groupBy('e.rSize')
->orderBy('e.rSize', 'ASC');
},
)
);
}
if ($bDisplayProduct) {
$builder->add(
'product',
EntityType::class,
array(
'class' => Products::class,
'choice_label' => 'sNumber',
'choice_value' => 'sNumber',
'placeholder' => '',
'label' => 'master.product',
'required' => false,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('e')
->groupBy('e.sNumber')
->orderBy('e.sNumber', 'ASC');
},
)
);
}
$builder->add(
'submit',
SubmitType::class,
array(
'label' => 'form.submit',
'attr' => array('class' => 'btn btn-primary'),
)
);
}
Other forms use the exact same code with more or less options.
I search a way to debug this on the production server (list/dump of 'blank' fields?).
Any hint will be appreciated, thanks !
Indeed I had some #Assert\NotBlank on several columns of an Entity.
Why the error was only on this server :
An instance (db record) of this Entity was NULL on those columns (which is an anormal behavior).
All the instances where retrieved to populate the form's dropdowns (as 'default' data).
It looks like the validator is checking the submitted 'data' AND those 'default' values since they are part of the form.
There were 4 asserted columns, so that's why I had 4 errors messages.
What I've done to find this out :
Added a dump($this->form->getErrors()) instruction on the callback processing the submitted form. It displayed the 4 entity's columns giving me hard time.
Went into db to see the corrupted record, and deleted it.
To prevent this in the future I might change the default values of these columns from NULL to something else, a basic string or a 0 value, and search the process that led to this corrupted record in db.
Thanks for your hints guys !

How do I limit number of rows in the admin form in magento

I have following code in my Form.php
$fieldset->addField('name', 'textarea', array(
'label' => Mage::helper('module')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'name',
));
I want to restrict the number of rows to display it like a single row, the code: 'rows' => 1 doesn't work here.
You can use styling to do this
$fieldset->addField('name', 'textarea', array(
'label' => Mage::helper('module')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'name',
'style' => "height: 1em;",
));
Just had to change 'textarea' to 'text'

How to build a single 'flag' checkbox in prestashop with form helpers?

I can't figure out from official docs how to build a single checkbox element from the standard helpers. I already have the relevant boolean entity in database and I can build radios or selects as well for it, and they work.
But what I'd really like is to have a single checkbox to use as a boolean flag.
Anyone knows how?
Ok, the answer is to just use the 'switch' type: that will build a 'slider' switch on backoffice page. For future reference, I'm gonna report 3 different ways to accomplish the same task: radio, select and switch.
They have all been tested on AdminAddressesController and are bound to a custom DB boolean field called 'expo'.
//SELECT
$s_options = array(
array( 'expo' => 1, 'name' => 'Yes' ),
array( 'expo' => 0, 'name' => 'No' )
);
$temp_fields[] = array(
'type' => 'select',
'label' => $this->l('Is Expo'),
'name' => 'expo',
'required' => false,
'options' => array(
'query' => $s_options,
'id' => 'expo',
'name' => 'name'
)
);
//RADIO
$s_options = array(
array( 'id' => 'expo_on', 'value' => 1, 'label' => $this->l('Yes')),
array( 'id' => 'expo_off', 'value' => 0, 'label' => $this->l('No')),
);
$temp_fields[] = array(
'type' => 'radio',
'label' => $this->l('Is Expo'),
'name' => 'expo',
'required' => false,
'class' => 't',
'is_bool' => true,
'values' => $s_options
);
//SWITCH
$s_options = array(
array( 'id' => 'expo_on', 'value' => 1, 'label' => $this->l('Yes')),
array( 'id' => 'expo_off', 'value' => 0, 'label' => $this->l('No')),
);
$temp_fields[] = array(
'type' => 'switch',
'label' => $this->l('Is Expo'),
'name' => 'expo',
'required' => false,
'is_bool' => true,
'values' => $s_options
);

Symfony set value checked on a form type choice

I create a form with FormBuilder with Symfony like :
$builder
->add('timeBarOpen', 'time', array('label' => 'Ouverture Bar', 'attr' => array('class' => 'form-control')))
->add('timeBarClose', 'time', array('label' => 'Fermeture Bar', 'attr' => array('class' => 'form-control')))
->add('timeStartHappyHour', 'time', array('label' => 'Début Happy Hour *', 'attr' => array('class' => 'form-control')))
->add('timeEndHappyHour', 'time', array('label' => 'Fin Happy Hour *', 'attr' => array('class' => 'form-control')))
->add('day', 'choice', [
'choices' => $days,
'multiple' => true,
'expanded' => true,
'label' => 'Jour(s) *',
])
;
$days is an array :
$days = array(
'Monday' => 'Lundi',
'Tuesday' => 'Mardi',
'Wednesday' => 'Mercredi',
'Thursday' => 'Jeudi',
'Friday' => 'Vendredi',
'Saturday' => 'Samedi',
'Sunday' => 'Dimanche',
);
So, this field type "choice" generates multiple checkboxes and I need them all to be checked by defaut when the form is created.
How can I do that?
You can use the data parameters to specify some default choices, in your case specify an array, and use the keys of your available choices
$builder
->add('day', 'choice', [
'choices' => $days,
'multiple' => true,
'expanded' => true,
'label' => 'Jour(s) *',
'data' => array_keys($days)
])
;
I had a similar problem with a ChoiceType drop-down list, where I wanted to be able to set the selected value, but I couldn't figure out how to do that. I figured it out from #ThomasPiard 's answer. Thank you!
In my example, I set the 'choices', and the 'data' is set to the value of the array (not the key). This is important - since I couldn't figure out why it didn't work at first.
Here's my sample:
->add('pet_type', ChoiceType::class, array( // Select Pet Type.
'choices' => array(
'Substitution' => 'sub',
'Equivalency' => 'equiv',
),
'label' => 'Select Petition Type:',
'attr' => array(
'onchange' => 'changedPetType()',
),
'placeholder' => 'Choose an option',
'data' => 'equiv',
))
Hopefully it will help someone with the same problem.

How can I render label to the right of the element?

I am adding a consent checkbox to an existing form. I am not able to render the label to the right of the checkbox. What am I doing wrong?
Please note that the check box has created using $this->addElement( because the rest of the form was created this way.
I thank you in advance.
$this->addElement('checkbox', 'isUserConsent', array(
'options' => array(array('placement' => 'APPEND')),
'label' => 'Plz activate',
'validators' => array(
array('InArray', false, array(
'hay' => array(1),
'messages' => 'Please check the consent box'),
)
),
'decorators' => array('ViewHelper','Errors','Label'),
));
The default is to prepend the label, but you can change this by modifying the decorator's 'placement' option:
$this->getElement('isUserConsent')->getDecorator('label')->setOption('placement', 'append');
Edit: I never use this syntax for decorators but it should be something like this:
$this->addElement('checkbox', 'isUserConsent', array(
'options' => array(array('placement' => 'APPEND')),
'label' => 'Plz activate',
'validators' => array(
array('InArray', false, array(
'hay' => array(1),
'messages' => 'Please check the consent box'),
)
),
'decorators' => array(
'ViewHelper',
'Errors',
'Label' => array(
'placement' => 'append'
)
),
));
This is the code for rendering lable of a form element.
$this->form->name->renderLabel() ;