How to set a class attribute to a Symfony2 form input
You can do this from the twig template:
{{ form_widget(form.birthdate, { 'attr': {'class': 'calendar'} }) }}
From http://symfony.com/doc/current/book/forms.html#rendering-each-field-by-hand
How to set a class attribute to a Symfony form input with an attribut from entity linked
I see you are using checkboxes.
Your code seems ok, and since you use query_builder, the values should be a Bed Entity. Note that attr
is not mentioned in the EntityType documentation, and I think you need to use choice_attr
instead.
Can you try this. I'm not sure if it will work or not:
$form->add('beds', EntityType::class, array(
'class' => 'DamiasResaBundle:Bed',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('b')
->orderBy('b.id', 'ASC');
},
'choice_label' => 'id',
'label' => 'lits ',
'multiple' => true,
'expanded' =>true,
'choice_attr' => function ($val) {
return ['class' => $val->getId()];
},
))
Let us know the results.
How to add class attribute in symfony form
Either you do it in your builder, controller or your view.
Controller :
$form = $this->createForm(new FormType(), $data, array('attr' => array('class' => 'class')));
View (Twig) :
{{ form_start(form, { 'attr' : { 'class': 'class' } })
As Joe pointed out source here
Symfony 2: setting form attributes in Form Class
If I understand your question, you want to set attributes but on your main form. Then, you should rely on $builder->setAttribute('data-custom', 'foo')
but, be aware this solution will set the attribute on the div wrapping your form not the form tag itself.
If you want to add attribute on the form tag, you will need to do it in your template via {{ form_start(form, { 'attr': { 'data-custom': 'foo' }}) }}
Set class (or any attribute) on Symfony2.4 form
The createFormBuilder method has two input parameters
public FormBuilder createFormBuilder(mixed $data = null, array $options = array())
So in your example you could use the second parameter to set the class on the whole form
private function createResolvedForm($id) {
return $this->createFormBuilder(null, array('attr' => array('class' => 'resolved-form exempt-from-default-ajax')))
->setAction($this->generateUrl('system_announcement_resolve', array('id' => $id)))
->setMethod('PUT')
->setAttribute('class', 'resolved-form exempt-from-default-ajax')
->add('submit', 'submit', array(
'label' => 'Mark As Resolved',
'attr' => array(
'class' => 'btn btn-success btn-xs',
'data-toggle' => 'tooltip',
'data-placement' => 'top',
'title' => 'Resolve Issue #' . $id,
)
))
->getForm();
}
Apply class to Symfony2 Form Label and Div
Fields are required
by default. You have to specify 'required' => false
to avoid it.
->add('email','text',array(
'required' => false,
'label_attr' => array(
'class' => 'CUSTOM_LABEL_CLASS'
),
))
About your second question, the simplest way would be to add code in the template :
{{ form_start(form) }}
<div class="myClass">
{{ form_widget(email) }}
</div>
{{ form_end(form) }}
Or create a new specific form block, or also modify existing one : http://symfony.com/doc/current/cookbook/form/form_customization.html#form-theming
Symfony2 Form Type - how to set form CSS class as attribute?
This can be done from several places:
- define in setDefaultOptions method of Form Type class
- As a parameter of
$this->createForm
function called from controller. - define in buildView method of Form Type class
- In template while rendering form
You just to know which option has precedence over another, and how they work.
Option 1: Here is the place to set default options. If no where else set the value this default value will be used.
Example Implementation (As Pivot provided):
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'attr' => array(
'class' => 'form-horizontal-from-default'
),
));
}
Option 2: You already know this, you can provide the attr value while calling $this->createForm
from controller(which is actually a shortcut for $this->container->get('form.factory')->create
function). When you provide this value, the value set from previous option will overridden.
Example Implementation (As You provided):
$this->createForm($formTypeObject, $entity, array(
'action' => 'URL,
'attr'=>array('class'=>'form-horizontal')
));
Option 3: You can set or override the value set by previous two option here. setting the value in buildView method. Declare following method in your Form Type Class:
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$options['attr']['class'] = 'form-horizontal-from-build-view';
//If you like to keep value set from previous methods you can define like
//$options['attr']['class'] = isset($options['attr']['class'])? $options['attr']['class'] :'';
//$options['attr']['class'] .= ' form-horizontal-from-build-view';
$view->vars = array_replace($view->vars, array(
'attr' => $options['attr'],
));
}
Option 4:: Now the final and ultimate way to set attributes. This has the height priority over other options, as it is done in the final stage while rendering the form.
You can define as follow in your template:
{{ form_start(form, {'method': 'POST', 'attr': {'class': 'form-horizontal-ultimate' }}) }}
Symfony2, How to set attribute class depending on value?
Just use the field attr option. According to your code, you assign the choices with your $choice
array, so the default choice will be the the first value in the array.
You could do something like this:
->add('month_report', 'choice', array(
'choices' => $choice,
'required' => true
'attr' => array('class' => 'select-' . array_keys($shoice)[0])
))
If you also want to change the class dynamically depending on the choice the user selects, you need to write some JS for that.
That said, I don't know why you say it "is not cool" to do this in Twig, because as it is style, it probably should be in the view component of your app... In fact, if you're writing JS to handle this anyway, why would you duplicate the presentation logic in the form builder?
Add a specific CSS-class to Symfony2 form
When you render a widget, you can add class with name foo, like this:
{{ form_widget(form.name, {'attr': {'class': 'foo'}}) }}
If you want to add class foo to form element (tag), then you can use the same syntax:
{{ form(form, { 'attr': {'class': 'foo'} }) }}
Check out official documentation.
add class atribute to symfony form builder row div
Symfony2/Twig has a wonderful form rendering engine; it'd be a waste to completely override it. As a much more elegant alternative, we can take advantage of the built-in form themes. As per the documentation:
Symfony comes with four built-in form themes that define each and every fragment needed to render every part of a form
We can override the default theme and create our own. This allows us to override the form_row
block, and add our own lovely attributes to the surrounding div
. Simply put this in a file, say: views/forms/fields.twig.
{% block form_row %}
<div class="form-group">
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock %}
We don't need to worry about the other declarations, as Symfony will overload only what's changed.
We can now reference it from the page template. Replace form
with the name of the form variable passed to the template:
{% form_theme form 'forms/fields.twig' %}
Of course, you're free to add a declaration to grab a form attribute instead of hard-coding the class name.
(Source: http://symfony.com/doc/2.7/cookbook/form/form_customization.html)
Related Topics
Round to Max Thousand, Hundred etc in PHP
How to Create Codeigniter Language Files from Database
How to Set 777 Permission on a Particular Folder
Permission Denied with Bash.Sh to Run Cron
Trying to Access Array Offset on Value of Type Null
Combine PHP Prepared Statments with Like
PHP Simplexml Attributes Are Missing
Invalid JSON Parsing Using PHP
Bad Request. Connecting to Sites via Curl on Host and System
How to Connect SQL Server with PHP Using Xampp
How to Add Dynamic Dropdown List Column on Laravel 5.3 Registration
Simplexml: Working with Xml Containing Namespaces
How to Construct a Cross Database Query in PHP
Int Variable with Leading Zero
How to Pass Custom Type Array to Postgres Function
How to Open a File from Line X to Line Y in PHP