Search code examples
symfonysonata-admin

Form Type Checkbox Checked for create form SonataAdminBundle


I'm struggling with this problem and can't find the solution. I just moved to SonataAdminBundle today.

I want to make default value as checked for checkbox type but just in form create SonataAdminBundle. In normal Controller, I can define create and edit function with different form value. But in SonataAdminBundle the create and edit form seems just in 1 function :

protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
             ->add('aktif', 'checkbox', array('required' => false))
        ;
    }

I've try add 'attr' => array('checked' => 'checked') but that also happens when editing data.


Solution

  • You can use the function getSubject() in the Admin class to see if you are in the create or edit form.

    Something like this:

    if (!$this->getSubject()->getId()) {
        // this is the create form
        $attrs = array('checked' => 'checked');
    }
    else {
        // this is the edit form
        $attrs = array();
    }
    

    and you write in options:

    'attr' => $attrs
    

    Good luck!