Version

Documentation » Admin

21. Integrate Symfony Workflow Component »

« 19. Persisting Filters

20. Creating an Admin with Annotations

If you are a fan of annotations, there is a 3rd party bundle that allows using annotations instead of creating admin classes.

20.1. Download the SonataAnnotationBundle

Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:

$ composer require kunicmarko/sonata-annotation-bundle

20.2. How to use

Let’s say we have a BlogPost entity that is connected to a Category entity like in the getting started chapter:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use KunicMarko\SonataAnnotationBundle\Annotation as Sonata;
// ...

/**
 * @Sonata\Admin("BlogPost")
 *
 * @ORM\Table
 * @ORM\Entity
 */
class BlogPost
{
    // ...

    /**
     * @Sonata\ListField()
     * @Sonata\FormField()
     *
     * @ORM\Column(name="title", type="string")
     */
    private $title;

    /**
     * @Sonata\ListAssociationField(field="name")
     * @Sonata\FormField()
     *
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="blogPosts")
     */
    private $category;

    // ...
}
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use KunicMarko\SonataAnnotationBundle\Annotation as Sonata;
// ...

/**
 * @Sonata\Admin("Category")
 *
 * @ORM\Table
 * @ORM\Entity
 */
class Category
{
    // ...

    /**
     * @Sonata\ListField()
     * @Sonata\FormField()
     *
     * @ORM\Column(name="name", type="string")
     */
    private $name;

    /**
    * @ORM\OneToMany(targetEntity="BlogPost", mappedBy="category")
    */
    private $blogPosts;

    // ...
}

Do not forget to clear your cache:

$ bin/console cache:clear

You are done and you probably want to know how this looks like in the admin interface. Well, let’s find out by going to http://localhost:8000/admin

Sonata Dashboard with SonataAnnotationBundle

The rest of the Annotation and their options can be found here.

Found a typo? Something is wrong in this documentation? Just fork and edit it!