Christian Kolb
Christian Kolb

Reputation: 1388

Sonata Admin Bundle - Different field options in configureFormFields

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?

Upvotes: 2

Views: 2712

Answers (2)

Tagarikdi Djakouba
Tagarikdi Djakouba

Reputation: 428

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);
}

Upvotes: 1

RobMasters
RobMasters

Reputation: 4148

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.

Upvotes: 6

Related Questions