Jun Rikson
Jun Rikson

Reputation: 1884

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.

Upvotes: 2

Views: 4261

Answers (3)

Thomas Kekeisen
Thomas Kekeisen

Reputation: 4406

The answers here are correct, but the best practice is to overwrite getNewInstance in your admin class like this:

public function getNewInstance()
{
    $instance = parent::getNewInstance();
    $instance->setAktif(true);

    return $instance;
}

Upvotes: 0

Pierre Vassoilles
Pierre Vassoilles

Reputation: 1

If you always have this problem, here's a possible solution :

In your entity class, in the __construct method, insert this code :

$this->aktif = true;

Upvotes: 0

Alexandru Togorean
Alexandru Togorean

Reputation: 153

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!

Upvotes: 3

Related Questions