Nico O
Nico O

Reputation: 14112

Add new data-attribute to a input type date in Form builder

At the moment i try to get started with symfony2, and are struggling at a task that is certainly easy to accomplish.

I've extended the DateType like this:

class Datepicker extends DateType
{

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        parent::setDefaultOptions($resolver);

        $resolver->setDefaults(array(
            'widget' => 'single_text',
            'format' => 'yyyy-MM-dd',
            'attr'  => [
                'data-format' => 'dd.mm.yy',
                'class' => 'date-picker'
            ]
        ));
    }

}

This works like expected. Now I'd like to add a new data attribute (data-min-date="0") to this type. For this I make this attemp in the form builder:

$builder
            ->add('eventDate', new Datepicker(),
            [
                'attr'  => [
                    'data-min-date' => '0',
                ]
            ])

It is kind of logical, that now all attributes except for the new data-attribute are gone.

My question is:

How can i append a new attribute and let the existing ones untouched? I hope not to have to do something like array_merge() here.

Update

Upvotes: 1

Views: 10430

Answers (1)

Nico Kaag
Nico Kaag

Reputation: 1886

This is expected behavior, simply because default options are defaults for when nothing is set, and if something is set, it should be overwritten.

You can solve this by writing an override for the buildForm method in your Datepicker class, that set the required extra options.

Here is what your class will look like (Not tested)

use Symfony\Component\Form\FormBuilderInterface;

class Datepicker extends DateType
{
    /**
    * {@inheritdoc}
    */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        if (!isset($options['attr']) || !is_array($options['attr'])) {
            // Should be an array as defined in the default options, but it doesn't hurt to mae sure
            $options['attr'] = array();
        }

        if (!isset($options['attr']['data-format'])) {
            $options['attr']['data-format'] = 'dd.mm.yy';
        }

        if (!isset($options['attr']['class'])) {
            $options['attr']['class'] = 'date-picker';
        } else {
            // Might want to do more checking to see if it already has a date-picker class
            $options['attr']['class'] .= ' date-picker';
        }
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        parent::setDefaultOptions($resolver);

        $resolver->setDefaults(array(
            'widget' => 'single_text',
            'format' => 'yyyy-MM-dd',
            'attr'  => []
        ));
    }

}

This way you force certain form options to be set, and still give the possibility for them to be overwritten.

Upvotes: 3

Related Questions