avris/micrus-crud

CRUD generator for Micrus framework

v4.0.0 2018-01-28 10:17 UTC

This package is auto-updated.

Last update: 2024-11-29 04:03:42 UTC


README

This is a module for Micrus framework which generates an admin panel based on simple configuration.

CRUD stands for "Create, Read, Update and Delete". This module offers you a tool to automatically generate an admin panel with those actions to be performed on database objects (Doctrine entities), along with listing them (with pagination, filtering and sorting).

Installation

Run:

composer require avris/micrus-crud

Then register the module in your App\App:registerModules:

yield new \Avris\Micrus\Crud\CrudModule;

On the frontend side, Crud's views use Bootstrap and Font Awesome 5

Configuration

To generate a CRUD for a specific model, just create a controller extending Avris\Micrus\Crud\Controller\CrudController:

/**
 * @Crud(
 *     "App\Entity\User",               -- class of the model to be handled by this controller
 *     form="App\Form\AdminUserForm",   -- form class (not required if edit & new are disabled)
 *     icon="fas fa-users",
 *     perPage=5,                       -- default 100
 *     metrics={                        -- what metrics to display in the dashboard
 *        "all": @CrudMetric("Avris\Micrus\Crud\Metric\CountMetric"),
 *        "lastWeek": @CrudMetric("Avris\Micrus\Crud\Metric\CountMetric", filters={"createdAt":">@ -1 week"}),
 *        "postsAvg": @CrudMetric("Avris\Micrus\Crud\Metric\AvgCountMetric", relation="posts"),
 *     },
 *                                      -- by default routes "list", "new", "edit", "show", "delete" are generated for all models
 *     disableRoutes={"new"},           -- unless some is removed like this
 *     addRoutes={"email": "/{__restr__:id}/email"} -- or added like this
 * )
 */
class UserController extends CrudController
{
    protected function configureList(ListConfig $config)
    {
        $config
            ->add('username', true)
            ->add('email', false, false)
            ->add('postsCount', false, false, false)
            ->add('roleName')
            ->add('createdAt')
            ->addAction('Crud/testEmail')
            ->addAction('Crud/impersonate')
        ;
    }

    protected function configureExport(ExportConfig $config)
    {
        $config
            ->add('username')
            ->add('email')
            ->add('postsCount')
            ->add('roleName')
        ;
    }

    protected function configureShow(ShowConfig $config)
    {
        $config
            ->add('username')
            ->add('email')
            ->add('roleName')
            ->add('posts', 'Post')
            ->add('createdAt')
        ;
    }

    public function emailAction(User $user, MailBuilder $mailBuilder, Mailer $mailer)
    {
        // implement like any other action
    }
}

A general config (not model-specific) can be set in config/crud.yml:

baseRoute: admin        # what all the generated routes should start with ("/admin/post/list")
perPage: 100            # number of items per page in the list view
dashboard: true         # enable/disable dashboard
idRestriction: uuid     # determines the restriction od ID in the generated routes (= whether to use "/admin/post/{uuid:id}/edit" or "/admin/post/{int:id}/edit" or something else)
cruds: {}               # instead of in the annotations, the model-specific config can be put here

The controller can provide methods that specify:

  • which fields should be used in the list view (configureList)
  • which in the export to a file (configureExport),
  • which in show view (configureShow),
  • which form to use when creating on entity (getNewForm),
  • and when editing it (getEditForm),
  • if any additional buttons should be added at the top (configureGeneral).
  • also, if you added some custom routes, obviously you need to handle them (here it's emailAction).

List view

When configuring list view, you can add columns using add, which has the following parameters:

  • name - attribute name (required)
  • key - (default: false)
    • false = just display the value
    • true = display the value as link to its details
    • string = display the value as link to {$key}_show
  • sortable - boolean (default: false)
  • filterable - (default: true)
    • true = enable standard filtering
    • false = disable filtering
    • array = filtering using a select box with values of the specified array
    • string = filtering with a select box out of all entities of type specified in $filterable
  • view - you can overwrite how the table cell is rendered by changing this field and creating a corresponding template (default: Crud/Show/element)
  • label - (default l("entity:{$modelName}.fields.{$fieldName}"))

You can also add new actions to the last column, using addAction($template), providing it with a name of a template to render there.

Show view

When configuring show view, you can add rows using add, which has the following parameters:

  • name - attribute name (required)
  • key - (default: false)
    • false = just display the value
    • true = display the value as link to its details
    • string = display the value as link to {$key}_show
  • row - do not escape the value, boolean (default: false)
  • view - you can overwrite how the table cell is rendered by changing this field and creating a corresponding template (default: Crud/Show/element)
  • label - (default l("entity:{$modelName}.fields.{$fieldName}"))

General settings

You can add new actions to the top bar, using addAction($template), providing it with a name of a template to render there.

Export settings

A list of elements can be exported to a file (built-in formats: csv, json, xml).

In configureExport method you can define a list of exportable fields for a given model. The second argument of add can be a callable ($entity, string $field) -> string, with which you can personalize the output (by default simple getters are used).

Hooks

The following methods of the CrudController will be executed at specific moments in entities lifecycle. Just overwrite them to hook into those moments.

create()
getNewForm($entity)
getEditForm($entity)
getForm($entity)

preCreate($entity)
postCreate($entity)
preUpdate($entity)
postUpdate($entity)
preDelete($entity)
postDelete($entity)

Customizing views

Feel free to adjust Crud's templates by simply overwriting it in your templates directory.

To list all the available CRUD's, you can use such code:

{% for crud, options in cruds if routeExists(crud ~ '_list') %}
    <li>
        <a href="{{ route(crud ~ '_list') }}">
            <span class="fa fa-fw {{ options.icon }}"></span>
            {{ ('entity:'~options.model~'.plural')|l }}
        </a>
    </li>
{% endfor %}

To link to the dashboard:

<a href="{{ route('admin_dashboard') }}">
    <span class="fa fa-dashboard"></span>
</a>

Copyright