2
votes

Is there a possiblity to add different fields to a Sonata Admin Bundle Form depending on wether you're creating a new entity or editing an existing one in configureFormFields?

2
You most likely want to use the Form Events - cheesemacfly

2 Answers

6
votes

I'm not sure if this is the best way, but I've accomplished this using:

protected function configureFormFields(FormMapper $form)
{
    // Add fields common to add AND edit...

    if ($this->getSubject()->getId() > 0) {
        // Add fields only when editing an existing object
    }
}

Obviously you could add an else condition too if you want to only be able to add fields for a new object.

1
votes

Here is a better way witch is recommended by the officiel documentation ( Click here )

$subject = $this->getSubject();

if ($subject->isNew()) {
    $formMapper->add('customField', TextType::class);
}

or you can do:

if ($this->isCurrentRoute('create')) {
    $formMapper->add('name', TextType::class);
}