Add custom class to Symfony form label - php

I am building a Symfony 2.7 form and I would like to be able to customise the labels.
At the moment I am able to define the labels using the form builder outlined in the Symfony docs, however I can't see any way to customise the CSS of the label without having to do it on the template.
I know that I would be able to add the CSS class by individually printing the form_label inside of a with my class, but I would prefer to keep it all inside of the form builder.
I've added my current form below for reference.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('dob_day', 'choice', array(
'required' => true,
'choices' => $dobDays,
'mapped' => false,
'attr' => array(
'label' => 'Day',
'class' => 'form-control'
)
))
->add('dob_month', 'choice', array(
'required' => true,
'choices' => $dobMonths,
'mapped' => false,
'attr' => array(
'label' => 'Month',
'class' => 'form-control'
)
))
->add('dob_year', 'choice', array(
'required' => true,
'choices' => $dobYears,
'mapped' => false,
'attr' => array(
'label' => 'Year',
'class' => 'form-control'
)
));
}

If you want to add some CSS to your HTML in the form type, use the style attribute.
->add('dob_year', 'choice', array(
'required' => true,
'choices' => $dobYears,
'mapped' => false,
'attr' => array(
'label' => 'Year',
'class' => 'form-control',
'style' => 'max-width: 4rem;'. // Concat. the styles across lines for clarity.
'border: solid 0.1rem teal;'
)
));
That said,
inside the formType is probably the last place I'd go looking to modify these elements' styles if I was the poor dev who had to maintain this form when you were gone.
While it's possible to add inline CSS here, don't put more than a few lines. If it grows to be more, add a class to some external 'main.css' then add that to your primary template (that all others inherit from) and you'll be able to reuse the styles you've made.
Last thought
This is actually pretty helpful when you're trying to make your formType modular and is why I wanted to answer :) Then I got carried away in a best practice mantra that came off as if this technique doesn't have its place, but it does!

Related

How do I style child elements of a drop down list in a Symfony form

I'm trying to style the dropdown options (label and checkbox) of a symfony form but am running into problems. I can style the rendered group of checkboxes and labels, but not each item (paired label + checkbox) individually.
I've attempted to style them by:
{{ form_widget(form.qualifications, {'attr': {'class':'d-block'} }) }}
But as detailed in the documentation, this only applies the styles to the parent element (the rendered group of options to select), not each individual option.
Here's the symfony form builder part which creates the widget
->add('qualifications', EntityType::class, [
'class' => Tag::class,
'multiple' => true,
'expanded' => true,
'required' => false,
'placeholder' => 'Select...',
'choices' => $this->tagsService->getTagsQualificationLevels(),
'attr' => [
'class' => 'form-control-ajax-submit-on-change w-20',
]
])
I expect to be able to apply styles to the choices array, but am really stuck on how to do so.
You can use the choice_attr option:
->add('qualifications', EntityType::class, [
'class' => Tag::class,
'multiple' => true,
'expanded' => true,
'required' => false,
'placeholder' => 'Select...',
'choices' => $this->tagsService->getTagsQualificationLevels(),
'attr' => [
'class' => 'form-control-ajax-submit-on-change w-20',
],
'choice_attr' => function($choiceValue, $key, $value) {
return ['class' => 'my_custom_choice_class'];
},
])
May be you should try for loop in template?
I had similar problems with radiobutton, take a look: How to make RadioButton in Symfony Form?

CollectionType of EntityType Symfony Forms

It is even possible to make ?
->add('product', CollectionType::class, [
'entry_type' => EntityType::class, array(
'data' => $options['product'],
'placeholder' => 'Wybierz klienta',
'multiple' => true,
'class' => Products::class,
'attr' => ['class' => 'chosen-select','data-placeholder'=>'Wybierz produkt'],
'choice_label' => function ($product) {
return ''.$product->getJson()["products"]["name"] .' | Stan Magazynowy: '.$product->getJson()["products"]["stock"].'';
},
'label' => 'Wybierz produkty'
),
'entry_options' => [
'label' => 'Value',
],
'label' => 'Add, move, remove values and press Submit.',
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'required' => false,
'attr' => [
'class' => 'my-selector',
],
])
I'll try to add chosen list of Products::class in CollectiontType, if some one wanna add product to new order, can add new EntityType and select product, and after submit i`ll handle this as array and save it to order.
If someone has another idea how to add products to form with quantity and then post it to array, please free to write :)
I think this is not the best way to do that.
You just have to add CollectionType to the FormType and update you ProductType class to handle if this is selected or not. May be you have to create a custom formtype for products for order only :-/ . All hard work are on the javascript side

cant translate name UploadButton in my Form

i got a problem in my form. Im translating all my fields with message.yml and it works. But i have also a upload button from VichUploaderBundle in it. I can translate the label, but when im testing it, the label is in english, but the button is in german.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id', TextType::class, array('disabled' => true))
->add('title',TextType::class, array('label' => 'edit.title'))
->add('body', TextareaType::class, array('label' => 'edit.body'))
->add('date', DateType::class, array('disabled' => true, 'label' => 'edit.date'))
->add('tags', EntityType::class, array(
'class' => 'AppBundle:Tag',
'choice_label' => 'getTitle',
'multiple'=> true,
'expanded'=> true))
->add(
'technology',
EntityType::class,
array(
'class' => 'AppBundle\Entity\Technology',
'choice_label' => 'getTitle',
'group_by' => 'parent.getTitle',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('t')
->where('t.parent IS NOT NULL')
->andWhere('SIZE(t.children) <= 0');
}
))
->add('imageFile', VichImageType::class, array(
'required' => false,
'allow_delete' => true,
'download_link' => true,
'label' => 'edit.image_file',
))
;
}
I dont know how to translate the button.
You are only creating a html file input.
This input does not have some label attribute.
<input type="file" name="imageFile"/>
-> the button label is set by your browser (which seems to be in german).
You can try to change it with CSS/JS
These text is defined by the browser and not by PHP or Symfony. You will also notice that this widget will be displayed differently in different browsers and on different operating systems. There is also no possibility to change the design of the widget. Most CSS properties won't have an effect on .
The only thing that you could do is to implement a custom JavaScript uploader, but that will probably only work in modern browsers.
I have not never done this, but a quick Google search brought up http://www.queness.com/post/11434/7-javascript-ajax-file-upload-plugins that features few JavaScript plugins to do this.

Access properties and methods of a class while configuring EntityType in Formbuilder::add()

I`ve got a dropdown list in my Symfony2 form like this:
$builder->add('categories','entity', array(
'class' => 'MyBundle:Myentity',
'property' => 'name',
'label' => 'Mylabel',
'expanded' => false,
'multiple' => false,
'label_attr' => array ( 'class' => 'control-label' ),
'attr' => array ( 'class' => 'form-control',
'placeholder' => 'Placeholder',
'title' => "Mytitle",
'data-toggle' => 'tooltip',
'data-myidfromDB' => '????',
'data-mynamefromDB'=>'????' etc. )));
So I am getting a list of MyBundle:Myentity objects and when I choose one I want to show all its properties (like ID, name, etc.) which are stored in my DB and described in Entity class, in different html data-* fields. If I select another one from the list I want to see all information related to my newly selected option in HTML (to change dynamically). Any ideas how to do that?
Since Symfony 2.7 you can set the option choice_attr to ChoiceType and set it a callable receiving the choice as an argument.
EntityType inherits this option and the choice in that case is the instantiated entity, so you can write something like :
$builder->add('categories','entity', array(
'class' => 'MyBundle:MyEntity',
'property' => 'name',
'label' => 'Mylabel',
'attr' => array('class' => 'form-control'),
'label_attr' => array('class' => 'control-label'),
'choice_attr' => function (\AppBundle\Entity\MyEntity $myEntity) {
return array(
'data-private-property' => $entity->getPrivateProperty(),
'data-some-value' => $entity->someMethod(),
);
},
);
You can't do that in easy way.
But you can put more information in select label.
Look on
http://symfony.com/doc/current/reference/forms/types/entity.html#choice-label
Yout can put here more field details and get it from your javascript.

Symfony2 Sonata Admin show attribute only as a readyonly text

I have some immutable attributes on my entity to administrate with sonata-admin bundle.
I want to show them in the edit-view of the entity, but don't want to provide any mechanism to change it (e.g. the value shall not be inside a input field)
I couldn't find anything but this:
$formMapper
->add('post', 'entity',
array(
'label' => 'Some post',
'attr' => array(
'readonly' => true,
'disabled' => true
),
'class' => 'Acme\DemoBundle\Entity\Post'
)
)
;
I tried it out with read_only, readonly, disabled etc. all the stuff. It looks ok, it's now inside a dropdown (since it is an entity) and I can not modify it.
But I even don't want that. I really need it as text (the current one).
Especially this is annoying if you use DoctrineExtensions with softdeletable, timestampable, since every "save" saves also the form-data.
Changing the type to 'text' instead of 'entity' replaces the dropdown with a input-field.. So, what's the best approach here?
$formMapper
->add('post', 'entity',
array(
'label' => 'Some post',
'read_only' => true,
'disabled' => true,
'class' => 'Acme\DemoBundle\Entity\Post'
)
)
;
This answer tells how to customize list rendering. Maybe the same approach works with form rendering?
If not, then you can create your custom form type according to create custom field type documentation, and customizing the template.
This is a bit old but this might help someone.
Here is the code that resolves your issue.
$formMapper
->add('post', 'entity', array('label' => 'Some post','attr' => array(
'readonly' => 'readonly',
'disabled' => 'disabled',
),
'class' => 'Acme\DemoBundle\Entity\Post')
)

Categories