Search code examples
phpsymfonysonata-adminsonata

How to disable radio buttons if one is seleced in Sonata Admin


For example I have an entity field which starts null and will show the radio buttons, within the Admin pages once a radio button has been selected and saved into the entity then those radio buttons need to be 'disabled', still visible but not intractable.

protected function configureFormFields(FormMapper $form)
{
    $form->add('radio_buttons', ChoiceType::class,
    array('choices' => array(
        "choice 1" => 'input1',
        "choice 2" => 'input2'),
        'choices_as_values' => true, 'multiple'=>false, 'expanded'=>true, 'disabled' => false));
}

Solution

  • Your can put a condition in your form to check wether a field is already filled or not. (Assuming the method is named getRadioButton())

    if ($this->getSubject()->getRadioButton() != null) {
        $form->add(here tell than you need disabled buttons)
    } else {
        $form->add(here tell than you need buttons)
    }
    

    also, in form field, you can add "html" attribute doing this:

    ->add('radio_buttons', ChoiceType::class,array(
        'what you want'=>'ok',
        'attr'=>array("disabled" => true))
    

    so finally it'd give something like

    if ($this->getSubject()->getRadioButton() != null) {
        $form->add('radio_buttons', ChoiceType::class,
        array('choices' => array(
             "choice 1" => 'input1',
             "choice 2" => 'input2'),
             'choices_as_values' => true,
             'multiple'=>false,
             'expanded'=>true,
             'attr' => array('disabled'=>true),
        ));
    } else {
         $form->add('radio_buttons', ChoiceType::class,
         array('choices' => array(
             "choice 1" => 'input1',
             "choice 2" => 'input2'),
             'choices_as_values' => true,
             'multiple'=>false,
             'expanded'=>true,
         ));
    }
    

    For more information:

    https://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/form_field_definition.html