Mayor of the Plattenbaus
Mayor of the Plattenbaus

Reputation: 1160

How to change ID field behavior after sonata:admin:generate

I have a fresh admin controller that extends Sonata's CRUDController class. I generated it using the sonata:admin:generate command.

There is also a new PostAdmin.php file that defines several field behaviors.

Here is a look at the table used by the entity:

mysql> DESC post;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int(11)      | NO   | PRI | NULL    | auto_increment |
| title  | varchar(255) | NO   |     | NULL    |                |
| author | varchar(255) | NO   |     | NULL    |                |
| slug   | varchar(255) | NO   |     | NULL    |                |
| body   | longtext     | NO   |     | NULL    |                |
+--------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

My question is: How do I go about making the ID field auto-populate in my CMS?

Right now, it shows up as a normal int field that users have to fill out, which introduces lots of potential for skipped numbers (not to mention being annoying for the users). I would like to change that.

Upvotes: 0

Views: 249

Answers (1)

Kamil Adryjanek
Kamil Adryjanek

Reputation: 3338

This can be achieve this by configuring the Form Mapper of your PostAdmin class:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('title', 'text')
        ->add('body', 'textarea')
    ;
}

You would need to remove the ->add('id') line so that it is not part of the form. Because it isn't necessary for the creation and should not be edited anyway.

Upvotes: 3

Related Questions