phpsymfonyconfigurationsonata-admin

How to set default configuration for Sonata sonata_type_date_picker


I know from Sonata Data Picker documentation that field configuration for sonata_type_date_picker can be passed with :

$builder
    ->add('publicationDateStart', 'sonata_type_datetime_picker', array(
            'dp_side_by_side'       => true,
            'dp_use_current'        => false,
            'dp_use_seconds'        => false,
    ))

But, is it possible to set some default configuration at an application level in a yml or xml file ?


Solution

  • One way you can achieve to set defaults for sonata's sonata_type_datetime_picker for application wide is to override the form type service for sonata_type_datetime_picker and in class parameter define your own class to handle defaults.

    1) Create a service file in your bundle form_types.xml and override sonata's service like

    <?xml version="1.0" encoding="UTF-8" ?>
    
    <container xmlns="http://symfony.com/schema/dic/services"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
        <services>
            <service id="sonata.core.form.type.datetime_picker" class="Acme\DemoBundle\Form\Type\DateTimePickerType">
                <tag name="form.type" alias="sonata_type_datetime_picker" />
                <argument type="service" id="sonata.core.date.moment_format_converter" />
            </service>
        </services>
    </container>
    

    In above service you can see i have defined a class that lies in Acme\DemoBundle

    2) Create a class in Acme\DemoBundle\Form\Type and name it as DateTimePickerType and extend this with sonata's BasePickerType class

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        /**
         * Here do what ever you need to change
         */
        $resolver->setDefaults(array_merge($this->getCommonDefaults(), array(
            'dp_use_minutes'     => true,
            'dp_use_seconds'     => true,
            'dp_minute_stepping' => 1,
        )));
    }
    

    3) Import your service file in main configuration file i.e config.yml

    imports:
        - { resource: parameters.yml }
        - { resource: security.yml }
        - { resource: @AcmeDemoBundle/Resources/config/form_types.xml }
    

    Full code demo visit Git Hub