sonata_type_model - Set value to empty - sonata-admin

Is there a way to allow to set an empty value in the sonata_type_model?
This is my current configuration:
->add('location', 'sonata_type_model', [
'class' => Location::class,
'property' => 'name',
'label' => 'Herkunft',
])

Simply add 'empty_value' => '' to the array.

Same problem here. I solved it with the help of Saving Hooks: preUpdate()
public function preUpdate($object)
{
if (!$this->getRequest()->request->get($this->getForm()->getName())['location']) {
$object->setLocation(null);
}
}

// Changed sonata_type_model to symfony entity type field
// Then add placeholder option witch recognized as empty value option in select box.
...
->add('location', null, [
'class' => Location::class,
'property' => 'name',
'label' => 'Herkunft',
'placeholder' => 'Your empty option label',
])

Related

prestashop multiple checkboxes do not save values

I can't figure out why the checkbox values are not saved in the database using helpers.
Trying to save some customers ids from my module's setting :
The array :
$custs = Customer::getCustomers();
foreach ($custs as $key => $value) {
$options[] = array(
'id_customer' => (int)$value['id_customer'],
'infos' => $value['firstname'].' '.$value['lastname'].' | '.$value['email']
);
}
The checkboxes :
'input' => array(
array(
'type' => 'checkbox',
'label' => $this->l('Customers'),
'desc' => $this->l('Select the Customers.'),
'name' => 'MY_MODULE_CUSTOMERS',
'values' => array(
'query' => $options,
'id' => 'id_customer',
'name' => 'infos',
),
),
)
The $_POST is always empty but works well with another input. Any help will be appreciated.
Thank you.
I don't think its in PS docs. But with a bit of code inspecting you can see in
Backoffice/themes/default/template/helpers/form/form.tpl
<input type="checkbox" name="{$id_checkbox}" id="{$id_checkbox}" class="{if isset($input.class)}{$input.class}{/if}"{if isset($value.val)} value="{$value.val|escape:'html':'UTF-8'}"{/if}{if isset($fields_value[$id_checkbox]) && $fields_value[$id_checkbox]} checked="checked"{/if} />
{$value[$input.values.name]}
add the porperty 'val' to option.
$options[] = array(
'id_carrier' => $carrier['id_carrier'],
'name' => $carrier['name'],
'val' => $carrier['id_carrier'],
);
Adn you get the desired serialization for the input values.
"transportistas" => array:2 [▼
0 => "73"
1 => "78"
]
Your code is correct, I tried it and this is result
http://screencast.com/t/wfsW86iJj
You have to click at least one checkbox.
Show data on server :
print_r($_POST);
die();
a better could be using groupbox but its quite difficult, take a look to the AdminCustomers controller class in the controllers directory of the prestachop, this has a multiselect group that used a relational table event stored in single field
If you want to be easy, using a single field to store in the database, take a look to THE COMPLETE CODE AND ALL THE STEPS AT: https://groups.google.com/forum/m/?hl=es#!topic/venenuxsarisari/z8vfPsvFFjk
at the begining dont forget to added that line:
// aqui el truco de guardar el multiselect como una secuencia separada por comas, mejor es serializada pero bueh
$this->fields_value['MY_MODULE_CUSTOMERS[]'] = explode(',',$obj->id_employee);
this $obj are the representation of the loaded previous stored value when go to edit ... from that object, get the stored value of the field of your multiselect, stored as "1,3,4,6"
and the in the field form helper list of inputs define the select multiple as:
array(
'type' => 'checkbox',
'label' => $this->l('Select and employee'),
'name' => 'MY_MODULE_CUSTOMERS[]',
'required' => false,
'col' => '6',
'default_value' => (int)Tools::getValue('id_employee_tech'),
'values' => array(
'query' => $options,
'id' => 'id_customer',
'name' => 'infos',
),
),
an then override the post process too
public function postProcess()
{
if (Tools::isSubmit('submitTallerOrden'))
{
$_POST['MY_MODULE_CUSTOMERS'] = implode(',', Tools::getValue('MY_MODULE_CUSTOMERS'));
}
parent::postProcess();
}
this make stored in the db as "1,2,3"

How to mark checkbox as selected using Bitwise in CakePHP?

I am developing an application in CakePHP 2.6 and I have a form where a user can set a series of flags when creating a calendar event.
I have managed to set up the 'add' action to display the flags and to also loop through in the controller after validation and save the value into my table. This process is done using bitwise. Code example below:
'add' action view:
echo $this->Form->input('flag', array('label' => false, 'type' => 'select', 'multiple' => 'checkbox', 'options' => $flagtypes, 'hiddenField' => false));
'add' action controller:
$flags = 0;
foreach ($data['flag'] as $r) {
$flags |= (int)$r;
}
I am however having trouble getting the checkboxes for the flags to be marked as selected in the edit action view when they are displayed.
'edit' action view:
$selected = array($results[0]['BitwiseFlag']);
echo $this->Form->input('flag', array('label' => false, 'type' => 'select', 'multiple' => 'checkbox', 'options' => $flagtypes, 'hiddenField' => false, 'selected' => $selected));
$results[0]['BitwiseFlag'] = 32 in the table.
$flagtypes array:
array(2) { [32]=> string(4) "Test" [64]=> string(9) "Testing 2" }
Not fully sure what your forms data structure looks like, but you should be able to set the flags from within your controller. Set the relevant values in $this->request->data, something like this:-
$this->request->data[$this->{$this->modelClass}->alias]['flag'] = [
0 => true,
1 => false,
2 => true
];
Then when you use $this->Form->input('flag', [...]) it should check the correct flags for you.
Change your input line to this :
$selected = array($results[0]['BitwiseFlag']);
// Change 'checked' to 'selected'.
echo $this->Form->input('flag', array('label' => false, 'type' => 'select', 'multiple' => 'checkbox', 'options' => $flagtypes, 'hiddenField' => false, 'selected' => $selected));

Adding a default option "Please Select" in cakephp dropdown

I am new to cakephp. I need to add a default
<option value="0">--Please Select--</option>
in my following select field :
$attributes = array("empty"=>false,"Selected" => 'Select City',"id" => "location");
echo $form->select("gal_location_id", $gal_locations,null,$attributes);
I tried to add
$gal_locations[0] = "--Select City--";
$attributes = array("empty"=>false,"default" => 0,"id" => "location");
but the option coming at the bottom of the list. What is the proper way to add the default option ?
You're looking for the "empty" attribute:
$this->Form->input('gal_location_id', array(
'type' => 'select',
'options' => $gal_locations,
'empty' => 'Select City', // <-- Shows as the first item and has no value
'id' => 'location'
));
See the equivalent in CakePHP3 from this post
CakePHP3
With the following option you dont get a notification to choose a dropdown item.
So if you're just looking for a default value and force the user to pick another, just replace the assign a string to 'empty'.
echo $this->Form->input('db_field', [
'label' => 'My Drop Down',
'empty' => [$default => $default], //Your default options
'options' => $my_options //Your array /list'
]);
echo $this->Form->input('country_id',[
`enter code here`'options' =>$country,
'label' => false,
'class'=>'form-control select2',
'empty'=> 'Select...',
'value' => ''
]);

Drupal allowed_values_function does not get called when creating a field

For some reason my allowed_values_function never gets called when showing a field on a user bundle. Code:
function get_business_units()
{
$options = entity_load('business_unit', FALSE, NULL, FALSE);
$opt = bu_to_list_values($options);
return $opt;
}
function MYMODULE_enable()
{
if (!field_info_field('field_user_business_unit')) {
$field = array(
'field_name' => 'field_user_business_unit',
'type' => 'text',
'settings' => array(
'allowed_values' => array(),
'allowed_values_function' => 'get_business_units',
)
);
field_create_field($field);
// Create the instance on the bundle.
$instance = array(
'field_name' => 'field_user_business_unit',
'entity_type' => 'user',
'label' => 'Business Unit',
'bundle' => 'user',
'required' => FALSE,
'settings' => array(
'user_register_form' => 1,
),
'widget' => array(
'type' => 'options_select',
),
);
field_create_instance($instance);
}
}
The field is created, and even displayed on the users "edit" page when editing their info. But the only value is "Select" or "None". My method is never called (I even placed a debug point). This is all in MYMODULE.install file.
The problem is: 'type' => 'text'.
You have to use: 'type' => 'list_text'.
Allowed values is meaningless for a text type.
Your get_business_units() function needs to be in the MYMODULE.module file; the .install files aren't included in a normal Drupal bootstrap.
Have you tried
drush features-revert MYMODULE ?

How to render a checkbox that is checked by default with the symfony2 Form Builder?

I have not found any easy way to accomplish to simply check a Checkbox by default. That can not be that hard, so what am i missing?
You can also just set the attr attribute in the form builder buildForm method:
$builder->add('isPublic', CheckboxType::class, array(
'attr' => array('checked' => 'checked'),
));
In Symfony >= 2.3 "property_path" became "mapped".
So:
$builder->add('checkboxName', 'checkbox', array('mapped' => false,
'label' => 'customLabel',
'data' => true, // Default checked
));
You would simply set the value in your model or entity to true and than pass it to the FormBuilder then it should be checked.
If you have a look at the first example in the documentation:
A new task is created, then setTask is executed and this task is added to the FormBuilder. If you do the same thing with your checkbox
$object->setCheckboxValue(true);
and pass the object you should see the checkbox checked.
If it's not working as expected, please get back with some sample code reproducing the error.
Setting the 'data' option works for me. I'm creating a non entity based form:
$builder->add('isRated','checkbox', array(
'data' => true
));
In TWIG
If you wish to do this in the template directly:
{{ form_widget(form.fieldName, { 'attr': {'checked': 'checked'} }) }}
Use the FormBuilder::setData() method :
$builder->add('fieldName', 'checkbox', array('property_path' => false));
$builder->get('fieldName')->setData( true );
"property_path" to false cause this is a non-entity field (Otherwise you should set the default value to true using your entity setter).
Checkbox will be checked by default.
To complete a previous answer, with a multiple field you can do that to check all choices :
'choice_attr' => function ($val, $key, $index) {
return ['checked' => true];
}
https://symfony.com/doc/3.3/reference/forms/types/choice.html#choice-attr
You should make changes to temporary object where entity is stored before displaying it on form. Something like next:
<?php
namespace KPI\AnnouncementsBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class AnnouncementType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
if ($options['data']->getDisplayed() === null) {
$options['data']->setDisplayed(true);
}
// ...
$builder
->add('displayed', 'checkbox', array(
'required' => false
));
}
}
As per documentation:
http://symfony.com/doc/current/reference/forms/types/checkbox.html#value
To make a checkbox or radio button checked by default, use the data option.
UserBundle\Entity\User
let's assume that you have an entity called ( User ) and it has a member named isActive, You can set the checkbox to be checked by default by setting up isActive to true:
$user = new User();
// This will set the checkbox to be checked by default
$user->setIsActive(true);
// Create the user data entry form
$form = $this->createForm(new UserType(), $user);
I had the same problem as you and here is the only solution I found:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$entity= $event->getData();
$form = $event->getForm();
$form->add('active', CheckboxType::class, [
'data' => is_null($entity) ? true : $entity->isActive(),
]);
});
This works as well, but aware of persistent "checked" state
$builder->add('isPublic', 'checkbox', array(
'empty_data' => 'on',
));
This is how you can define the default values for multiple and expanded checkbox fields. Tested in Symfony4, but it has to work with Symfony 2.8 and above.
if you want to active the 1st and the 2nd checkboxes by default
class MyFormType1 extends AbstractType
{
CONST FIELD_CHOICES = [
'Option 1' => 'option_1',
'Option 2' => 'option_2',
'Option 3' => 'option_3',
'Option 4' => 'option_4',
'Option 5' => 'option_5',
];
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->addSettingsField('my_checkbox_field', ChoiceType::class, [
'label' => 'My multiple checkbox field',
'choices' => self::FIELD_CHOICES,
'expanded' => true,
'multiple' => true,
'data' => empty($builder->getData()) ? ['option_1', 'option_2'] : $builder->getData(),
]);
}
}
if you want to active every checkbox by default
class MyFormType2 extends AbstractType
{
CONST FIELD_CHOICES = [
'Option 1' => 'option_1',
'Option 2' => 'option_2',
'Option 3' => 'option_3',
'Option 4' => 'option_4',
'Option 5' => 'option_5',
];
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->addSettingsField('my_checkbox_field', ChoiceType::class, [
'label' => 'My multiple checkbox field',
'choices' => self::FIELD_CHOICES,
'expanded' => true,
'multiple' => true,
'data' => empty($builder->getData()) ? array_values(self::FIELD_CHOICES) : $builder->getData(),
]);
}
}
The only watertight solution for me in Symfony 4, 2022 is:
OPTION 1:
First, set it default to "true" on the entity parameter itself:
class MyEntity {
/**
* #ORM\Column(name="my_param", type="boolean", nullable=true)
*/
private $myParameter = true;
...
}
Secondly, in the form, first see if you can get it from the entity itself. If Not, set the default
public function buildForm(FormBuilderInterface $builder, array $options)
{
/** #var MyEntity $entity */
$entity = $builder->getData();
$builder->add('myParameter', CheckboxType::class, [
'required' => false,
'data' => $entity ? $entity->getMyParameter() : true,
]);
}
This way the real value (coming from the database) has precedence over the default value.
Also good to know is: Submitted data has precedence over the 'data' => true but initially loaded data before submit gets overridden by 'data' => true
OPTION 2:
An alternative way of setting it default true on the MyEntity Class you can choose to set it as default only just before creating the form.
But then you always need the object to create the form with. So you then may not create a form without a given object
if (empty($entity)) {
// Warning: Only if it's a new object, set the default
$entity = new MyEntity();
$entity->setMyParameter(true);
}
// For this option you must always give the form an entity
$form = $this->createForm(MyType::class, $entity);
$form->handleRequest($request);
So for this option you don't need to do anything special in the FormType
$builder->add('myParameter', CheckboxType::class, [
'required' => false,
]);

Resources