Search code examples
symfonysonata-adminsonata

Sonata Admin compile form field from query string


In Sonata Admin is it possible to set or precompile a value in a form taking it from the query string?

I have a custom page with a calendar and when I click a date on the calendar I would like to be redirected to the create page of an event where the date is already set from the query string. Something like:

http://localhost:8000/admin/app/event/create?date=2017-07-11


Solution

  • I solved it by using the request service and a field marked as 'mapped' => false on my form builder:

    protected function configureFormFields(FormMapper $formMapper)
    {
        $request = $this->getRequest();
        $dateParameter = $request->query->get('date');
        $date = null;
    
        if ($dateParameter) {
            $date = \DateTime::createFromFormat('!Y-m-d', $dateParameter);
        }
    
        if (!$date) {
            $formMapper
                ->add('date', DatePickerType::class)
                ->add('calendarDate', HiddenType::class, array(
                    'data' => null,
                    'mapped' => false,
                ))
            ;
        } else {
            $formMapper
                ->add('date', DatePickerType::class, array(
                    'data' => $date,
                    'disabled' => true,
                ))
                ->add('calendarDate', HiddenType::class, array(
                    'data' => $date->format('Y-m-d'),
                    'mapped' => false,
                ))
            ;
        }
    
        $formMapper
            // other fields
            ->add('other_field', ModelType::class)
        ;
    }
    

    Then, on the following method I am updating the entity field:

    public function prePersist($myEntity)
    {
        $this->preUpdate($myEntity);
    }
    
    public function preUpdate($myEntity)
    {
        $dateString = $this->getForm()->get('calendarDate')->getData();
        if ($dateString) {
            $date = \DateTime::createFromFormat('!Y-m-d', $dateString);
            if ($date) {
                $myEntity->setDate($date);
            }
        }
    }
    

    In this way I can use my form with or without the query string parameter date:

    http://localhost:8000/admin/app/event/24/edit?date=2017-07-01

    enter image description here

    And in the HTML I have this:

    <input type="hidden" id="s59664a9ea44ce_calendarDate" name="s59664a9ea44ce[calendarDate]" class=" form-control" value="2017-07-01" />
    

    P.S. when someone gives a -1 it should be nice to explain why...