Symfony form read only field - symfony

How should I render read-only fields using Symfony form component?
This is how I am trying to do that to no avail:
Symfony 2
$builder
->add('descripcion', 'text', array(
'read_only' =>'true'
));
}
Symfony 3
$builder
->add('descripcion', TextType::class, array(
'read_only' => 'true'
));
}

Provided answers all end up with this exception on Symfony 3:
Uncaught PHP Exception Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException: "The option "read_only" does not exist.
The right way to do this is to take advantage of attr property on the field:
->add('descripcion', TextareaType::class, array(
'attr' => array(
'readonly' => true,
),
));
If you are after way to have a field with data not posted to the server during form submission, you should use disabled like:
->add('field', TextareaType::class, array(
'disabled' => true,
));
on your form builder object.

I believe the only secure method to present a form field as readonly and also prevent your form from accepting a new value in a request is the following.
$builder->add(
'description',
TextType::class,
['disabled' => true]
);
The other suggestion of using either ['attr' => ['readonly' => true]] or ['attr' => ['disabled' => true]] will leave you vulnerable to forged requests.
Both the latter options will set either readonly or disabled attributes on the field, but your Form will still accept a new value for this field if included in the request.
Only the first option above will both disable the form field and also prevent your Form from accepting a new value for the field in the request.
I have tested this with Symfony Form 3.4. I do not know if 4 behaves the same.

You have declared your read only attribute to a string, it needs to be a boolean.
remove the quotes around true
like this:
->add('descripcion','text',array('read_only' => true))
true, without the quotes.

Symfony 4 allows using only "disabled" option in form field. But it is something different that "readonly".
Disabled - user can't edit field and its value IS NOT passed during form submision.
Readonly - user can't edit field but its value IS passed during form submision.
Only solution I found for "readonly" is:
->add('fieldname', TextType::class, [
'label' => false,
'attr'=> [ 'readonly' => true ]
])

read_only is deprecated since Symfony 2.8. So please use readonly instead. And provide boolean value for this attribute
->add('','text',array('readonly' => true))

Update: since Symfony 3.0, the readonly value should be set in the attr option.
http://symfony.com/doc/2.8/reference/forms/types/form.html#read-only
The disabled option can also be used instead.

Would recommend using the disabled option because any submitted value will be ignored as per the docs: https://symfony.com/doc/current/reference/forms/types/text.html#disabled
$builder->add('descripcion', TextType::class, [
'disabled' => 'true',
]);

readonly and not read_only. You shoud make this option in attr like this:
->add('', TextType::class, array('attr'=> array('readonly' => true)))

Let me add something that the other answers didn't help to manage with. The treatment as field but "tweak" to disable edition may work in many cases. However, it's at least difficult to render in some formats that fully prevent edition (i.e., render as a label).
How to solve this? What I did is to define the field as HiddenType, and in the template, render using {{ form.vars.value.myfield }} or {{ item.myfield }} taking "item" as the entity object, enclosed in whatever you can think of, as any other HTML element.

Other solution could be:
->add('value', TextType::class, ['disabled' => true]):
Taken from: http://symfony.com/doc/current/reference/forms/types/text.html#disabled

Only 'disabled' option does not cause an error
$builder
->add('descripcion', TextType::class, array(
'disabled' => 'true'
));
}

If familia and proveedor are relations to other entity i think they shouldn't be text type. Try nullify their types or change to entity type and check if it worked.

Related

Is it possible to use CollectionType with LanguageType class ? Symfony

I am trying to build a form and propose a language selection. I want this selection to duplicate when the user wants to add several languages.
My question is : Is it possible to use CollectionType with LanguageType class ?
Thank you.
Yes, absolutely.
Check out one of the examples in the Docs:
$builder->add('emails', CollectionType::class, [
// each entry in the array will be an "email" field
'entry_type' => EmailType::class,
// these options are passed to each "email" type
'entry_options' => [
'attr' => ['class' => 'email-box'],
],
]);
It is totally up to you to specify the underlying form type to be used, whether it is TextType or LanguageType. And you configure the type via the entry_options key.
Hope this helps...

Symfony - Disable required field if the checkbox is checked

I have a form on Symfony.
My form is composed of a text input and a checkbox.
If the user checks the box, the input text is disabled (I use javascript).
However, if the user doesn't check the box, he has to fill in the input text. If he ticks the box, he does not have to do it.
Here is my form :
$formBuilder
->add('text', TextType::class,array(
'required' => true,
'constraints' => array(
new NotBlank()
)))
->add('box', CheckboxType::class, array(
'mapped' => false,
'label' => 'Box'
))
;
I'm looking for a way to disable text input validation if the box is checked.
How to ignore input text validation if the checkbox is checked?
Do you know how to do this?
Thanks!
You need a custom contraint in this case. You should mark field as non-required and show asterisk (*) for required using javascript. For the backend, you need to create a custom constraint. See symfony documentation here: https://symfony.com/doc/current/validation/custom_constraint.html

Use the category node name as a label in Zikula

I do use Zikula 1.5.2dev
My module is generated with modulestudio
I have made two entries in the Category registry. One is showing at the node "Global" and one at the node "Type"
In Global are several entries I can select. Some other entries are inside Type.
The selection is working in my template like expected. But how can I use the node names as a label?
I can not figure out in which template I have to place to label (have to do more searching). But more important, I do not know the right twig syntax to catch the categories label.
if you assign a category to the template, the properties are accessible like normal class properties.
{{ category.name }}
if you need the display name, this is stored as an array with lang codes as keys
{{ category.display_name['de'] }}
Hope that helps.
That sounds good. But now I have recognized this label seem not to be placed in a pure template. There is a form type defined:
class ShowRoomItemType extends AbstractShowRoomItemType
{
/**
* #inheritDoc
*/
public function addCategoriesField(FormBuilderInterface $builder, array $options)
{
$builder->add('categories', CategoriesType::class, [
'label' => $this->__('Category') . ':',
'empty_data' => null,
'attr' => [
'class' => 'category-selector'
],
'required' => false,
'multiple' => false,
'module' => 'RKShowRoomModule',
'entity' => 'ShowRoomItemEntity',
'entityCategoryClass' => 'RK\ShowRoomModule\Entity\ShowRoomItemCategoryEntity',
// added:
'includeGrandChildren' => true
]);
}
}
In my template it is called like this:
{{ form_row(quickNavForm.categories) }}
For this my skills are very limmited. I will write a feature request at modulestudio. (https://github.com/Guite/MostGenerator/issues/1147)
But big thanks for your reply!
This has been fixed for core 1.5.4 / 2.0.4 in https://github.com/zikula/core/pull/3846

Sonata admin, editable field with choice

I'm using sonata admin and there is an option 'editable' => true for edit directly inline datas on the list view.
If my field is a text, it's ok, i can click, edit the text and save directly on the table.
But i don't want an input type="text" when i click on the field, but a list, i'm trying something like :
->add('etat', null, array('editable' => true), 'choice', array(
'choices' => array(
'Brut' => 'Brut',
'NRP' => 'NRP',
)
))
But no effetc.. is this possible ?
Since Sonata Admin Bundle 2.2 choice accepts the "editable" parameter in the list view. You use it like that:
$listMapper->add('etat', 'choice', [
'choices'=>['Brut'=>'Brut', 'NRP' => 'NRP',],
'editable'=>true,
]);
Doc: https://sonata-project.org/bundles/admin/2-2/doc/reference/field_types.html
It's possible for scalar values only. Hear some doc
http://sonata-project.org/bundles/admin/master/doc/reference/field_types.html
Well it's not possible at the moment and won't be possible as I can guess in the near future. Your own realization should be written.

datagrid filter for relation object as text field (insted of dropdown) in sonata admin in symfony 2.4

I have entity 'Action' with relation to 'User'. Created Admin CRUD controller in SonataAdminBundle. Everything works fine except user filter is rendered as dropdown list. I have 8k user count and growing so you must see why this is a problem.
I want user filter to be text input and on submit to search with LIKE %username%
Right now I add user filter like this - $datagridMapper->add('user').
I know I can add filter type and field type but I am not able to find the right combination and options. Found information on http://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/filter_field_definition.html but still no success.
Final solution
Following Alex Togo answer I used this code:
$datagridMapper->add('user', 'doctrine_orm_callback', array(
'callback' => function($queryBuilder, $alias, $field, $value) {
if (empty($value['value'])) {
return;
}
$queryBuilder->leftJoin(sprintf('%s.user', $alias), 'u');
$queryBuilder->where('u.username LIKE :username');
$queryBuilder->setParameter('username', '%'.$value['value'].'%');
return true;
},
'field_type' => 'text'
))
I needed something like this on a project. I implemented this feature using this. You can try to set the 'field_type' option to 'text' (I used 'choice' in the project I worked at) and add the querybuilder actions you need to filter.
Use doctrine_orm_choice option.
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper->add(
'module',
'doctrine_orm_choice',
[],
'choice',
[
'choices' => $this->filterModuleList
]
)
....

Resources