1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Drupal】entityを定義した時のルーティング設定

Posted at

Drupalのルーティングで発見があったのでメモとして残す。

現在まで書いていた書き方

member.routing.yml

entity.member.canonical:
  path: '/admin/member/{member}'
  defaults:
    _entity_view: 'member.full'
    _title: 'Member'
  requirements:
    _permission: 'administer site configuration'

entity.member.edit_form:
  path: '/admin/member/{member}/edit'
  defaults:
    _entity_form: 'member.edit'
    _title: 'Edit Member'
  requirements:
    _permission: 'administer site configuration'
# 削除や編集など続くルーティングを記述

当初よくある、crudのルーティングをrouting.ymlに記述していた。
ただ、ContentEntityBaseを継承したエンティを作成する場合、必ず?linksにurlを記述しないと行けないので
どちらにもurlを記述しないといけなく面倒だなと思っていた。

簡略化

Member.php
<?php

namespace Drupal\member\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Defines the Member entity.
 *
 * @ContentEntityType(
 *   id = "member",
 *   label = @Translation("Member"),
 *   base_table = "members",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name"
 *   },
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\member\MemberListBuilder",
 *     "views_data" = "Drupal\member\MemberViewsData",
 * 
 *     "form" = {
 *       "default" = "Drupal\member\Form\MemberForm",
 *       "add" = "Drupal\member\Form\MemberForm",
 *       "edit" = "Drupal\member\Form\MemberForm",
 *       "delete" = "Drupal\Core\Entity\EntityDeleteForm"
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
 *     }
 *   },
 *   admin_permission = "administer site configuration",
 *   links = {
 *     "canonical" = "/admin/member/{member}",
 *     "edit-form" = "/admin/member/{member}/edit",
 *     "delete-form" = "/admin/member/{member}/delete",
 *     "collection" = "/admin/member",
 *     "add-form" = "/admin/member/add"
 *   },
 * )
 */
class Member extends ContentEntityBase
{
}

Entityにroute_providerを指定することで、自動的に設定してくれる様になる。
よくあるcrudのルーティングに関してはDrupalのコアファイルにAdminHtmlRouteProviderを指定するだけで、自動的にurlを設定してくるのでrouting.yamlを記述しなくて良くなる

逆にrouting.yamlを使う場合はEntityを使わずにControllerBaseから継承したControllerから何かしたい場合は記述する方法しか無いと思う。
eccubeとかなら、@ Routea アノテーションを使えたりするけど、drupalには無いと思う。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?