Search code examples
symfonysonata-admin

Time picker (no date) in a Sonata-admin form


I'm upgrading a Symfony project's Sonata Admin usage, from Sonata-Admin 2.2 to 2.3, as part of upgrading the overall project to Symfony 2.7.

We have a number of 'time' fields (that is, defined in Doctrine as "time", with no meaningful date component.)

In Sonata-Admin 2.2 the FormMapper definition was simple:

$formMapper
   ->tab('tab.general')
   ->add('start', null, array('label' => 'label.start')
   ->end()

and that gave the layout of "half-form-width" Hour and Minute selection boxes, side by side, in the form:

enter image description here

But Sonata-Admin 2.3 is showing them over two full lines:

enter image description here

which is not so nice or useable.

So, what should I be setting to get the same rendering?

I've tried using the 'sonata_type_datetime_picker' but that is really insistent on displaying a date. These fields do not have a date. There seems to be no equivalent for just picking the time.


Solution

  • Had the same issue and solved it by adding my own CSS file for overrides.

    1) Add class to your form field

    ->add('start', 'time', array(
        'attr' => array('class' => 'fixed-time')
    ))
    

    2) Create a new CSS file in your bundle under Resources/public/css/override.css with overrides by fixed-time class

    For example:

    .fixed-time .select2-container {
        width: auto !important;
    }
    

    3) Then somewhere in your bundle (Resources/views) create a new template called standard_layout.html.twig and override Sonata template + add newly created CSS file (remember to call parent() first, to load sonata code first).

    {% extends 'SonataAdminBundle::standard_layout.html.twig' %}
    
    {% block stylesheets %}
        {{ parent() }}
        <link rel="stylesheet" href="{{asset('bundles/yourbundle/css/override.css')}}" type="text/css" media="all"/>
    {% endblock %}
    

    4) Then register your standard_layout twig template into Sonata admin (in your config.yml).

    sonata_admin:
        templates:
            layout: YourBundle::standard_layout.html.twig
    

    Do not forget to install new assets (assets:install) and clear cache (remove selected folder from app/cache), otherwise you will not see any change.