メインコンテンツに移動
ホーム

古松

メインナビゲーション

  • ホーム
  • ビデオ
  • ご連絡

パンくず

  • ホーム
  • DrupalのEntityを定義する簡単な例

DrupalのEntityを定義する簡単な例

Entityを定義する簡単な例:Roomエンティティ(Entityのサンプロモジュール:entity_example)

  • Entityをプログラミングで定義するには、最初簡単なこと、必要最小限のことを定義します
  • ここで、ルーム(Room)エンティティ(Entity)を例として紹介します(サンプルモジュールをダウンロードしてください)
    Roomエンティティ例とします

Roomエンティティ:Entityの定義 + データインポート + Entityの参照

  • Roomのテストデータ(dsvフォーマット): 

    • ルームナンバー: room_number

    • ルームタイプ:: type
      rid,room_number,type
      1,1001,シングル
      2,1002,シングル
      3,1003,シングル
      4,2001,ダブル
      5,3001,ダブル
  • データベース上に「room」テーブルを作成、または、モジュールのinstallファイルでスキーマを定義して、モジュールがインストール時に自動的に作成されます
    /**
     * Implement hook_schema()
     */
    function entity_example_schema(){
        $schema['room']=array(
            'description' => 'Rooms',
            'fields' => array(
                'rid' => array(
                    'type' => 'serial',
                    'description' => 'Room Id'
                ),
                'type' => array(
                    'type' => 'varchar',
                    'length' => '255',
                    'description' => 'Room Type'
                ),
                'room_number' => array(
                    'type' => 'varchar',
                    'length' => '25',
                    'description' => 'Room Number'
                ),
    
            ),
            'primary key' => array('rid'),
    
        );
    
        return $schema;
    }
  • モジュールファイル(.module)にRoomエンティティを定義します
    /**
     * Implements hook_entity_info().
     */
    /**
     * Implements hook_entity_info().
     */
    function entity_example_entity_info()
    {
    
       $services['room'] = array(
            'label' => t('Room'),                       // エンティティ名
            'entity class' => 'Entity',                 // デフォルトクラスの使用
            'controller class' => 'EntityAPIController',// デフォルトクラスの使用
            'base table' => 'room',                     // DB上のテーブル名
            'fieldable' => TRUE,                        // 余分のフィールド追加可能
            'entity keys' => array(                     // ルームIDをエンティティのキー.
                'id' => 'rid',
                'label' => 'room_number',               // コールバック関数が優先
            ),
            'view modes' => array(
                'full' => array(
                    'label' => t('Default'),
                    'custom settings' => FALSE,
                ),
            ),
            'bundles' => array(),                       // bundleはこのエンティティ自身
    //        'label callback' => 'room_label',       // 指定しないとラベルの取得ができない
            'access callback' => 'room_access' ,        // default:'value user_access'動作しない
            'module' => 'entity_example',
            'metadata controller class' => 'EntityExampleMetadataController',
    
        );
    
        return $services;
    }
    
    /**
     * Extend the defaults.
     */
    class EntityExampleMetadataController extends EntityDefaultMetadataController {
        public function entityPropertyInfo() {
            $info = parent::entityPropertyInfo();
            $properties = &$info[$this->type]['properties'];
            $properties['type'] = array(
                'label' => t('Room type'),
                'schema field' => 'type',
                'getter callback' => 'entity_property_getter_method',
                'setter callback' => 'entity_property_verbatim_set',
                'required' => TRUE,
                'description' => t('Room type of the room'),
            );
            $properties['room_number'] = array(
                'label' => t('Room Number'),
                'schema field' => 'room_number',
                'getter callback' => 'entity_property_getter_method',
                'setter callback' => 'entity_property_verbatim_set',
                'required' => TRUE,
                'description' => t('The number of the room'),
            )
            return $info;
        }
    }
    
    function room_access($op, $room = NULL, $account = NULL) {
        // 全員アクセス可能にする
        return TRUE;
    }
    
    
  • これだけで、Entityの定義が完了しました
  • モジュール(Feeds)でRoomサンプルデータをDBにインポートします
    • モジュール(Feeds Entity Processor)のインストール/有効化が必要
  • 実際にRoomエンティティが動作しているかをテストします
    • 任意のコンテンツタイプ(例:記事)Roomフィールドを追加します(Entity参照タイプ)
    • Entity参照タイプのターゲットを「Room」にします
    • 一つの記事を作成して、Roomエンティティの動作を確認します

Enity定義の注意点:アクセス権限、エンティティのラベル定義を正しく定義します

  • 上記例として、Entityの必要な最低限な定義となります
  • ネットでEntity定義例がありますが、アクセス権限、エンティティのラベルなどの権限が間違いやすいです
  • アクセス権限(access callback)で定義しないと、エンティティのラベルがうまく表示されないです
    Entityのアクセスコールバックが定義しないとラベルがうまく表示されない
  • エンティティのラベルを2か所で定義できます
    • entity_keys: DB上にどのフィールドがラベルとして利用するかを指定します
    • label callback : ユーザー必要応じて、ラベルを生成するコールバック関数
    • コールバック関数がentity_keys設定より優先です
      Entityのラベル設定

 

 

 

entity_example.zip

DrupalのEntityを定義する簡単な例-2:エンティティ管理フォーム

Entityの管理フォーム:一覧表示/追加/削除/更新 操作ができるようにする

  • 前回紹介した(DrupalのEntityを定義する簡単な例 )では、データを直接にDBに書き込むか、Feedsでcsvフォーマットデータをインポートする方法となります
    • 前回の例に一つEntityプロパティを追加します(sys_name)
    • これはコンテンツタイプなどを追加するときによく見られる名前とシステム名のペアです
    • 今回の例では:名前は「room_number」、システム名は「sys_name」にします
    • DBにもこのフィールドを追加します(カスタムモジュールのinstallファイルにあるスキーマに記入しました)
  • モジュール(Entity API)がEnitityに関する管理フォームが提供しています
    • 今回のカスタムモジュール(entity_example_2.zip)をダウンロードして、テストサイトにインストールし、動作を確認できます
    • 作成されたEntity一覧の表示
      EntityAPIに提供されたエンティティ一覧表示
    • Entityの新規作成/編集/追加操作もあります
      EntityAPIに提供された追加/更新/削除操作

Entityの管理フォームを表示させるため「EntityAPIControllerExportable」を使用します

  • Entityを定義(hook_entity_info() )する部分に「controller class」を「EntityAPIControllerExportable」を使用します
        $services['room'] = array(
            'label' => t('Room'),                       // エンティティ名
            'entity class' => 'Entity',                 // デフォルトクラスの使用
            'controller class' => 'RoomController',     // EntityAPIControllerExportableの使用
    //        'controller class' => 'EntityAPIController',// <-前回使用したもの: デフォルトクラスの使用
            'base table' => 'room',                     // DB上のテーブル名
            ・・・・・・・
        );
    
    // Entityの「controller class」のコールバッククラス
    class RoomController extends EntityAPIControllerExportable {
        public function __construct($entityType) {
            parent::__construct($entityType);
        }
    
        /**
         * Create a room - we first set up the values that are specific
         * to our room schema but then also go through the EntityAPIController
         * function.
         */
        public function create(array $values = array()) {
            // Add values that are specific to our Room
            $values += array(
                'rid' => '',
                'is_new' => TRUE,
                'type' => '',
                'room_number' => '',
                'sys_name' => '',
            );
            $room = parent::create($values);
            return $room;
        }
    }
  • Entity管理フォームをコンテンツ管理ページ(例)に挿入するために「admin ui」パラメターを定義します
    /**
     * Implements hook_entity_info().
     */
    function entity_example_entity_info()
    {
        $services['room'] = array(
            'label' => t('Room'),                       // エンティティ名
            'entity class' => 'Entity',                 // デフォルトクラスの使用
       ・・・・・
            'module' => 'entity_example',
            'metadata controller class' => 'EntityExampleMetadataController',
            'admin ui' => array(
                'path' => 'admin/structure/rooms',
                'file' => 'rooms.admin.inc',
                'controller class' => 'RoomsUIController',
            ),
    
        );
    
        return $services;
    }
  • 管理UI定義は「rooms.admin.inc」ファイルに書きこみます(room.module内で記述することもできます)
    /**
     * UI controller.
     */
    class RoomsUIController extends EntityDefaultUIController {
    
      /**
       * Overrides hook_menu() defaults.
       */
      public function hook_menu() {
        $items = parent::hook_menu();
    	$items[$this->path]['description'] = t('Manage rooms. including adding
    		and removing fields and the display of fields.');
        return $items;
      }
    }
    
    /**
     * Generates the room editing form.
     */
    function room_form($form, &$form_state, $room, $op = 'edit') {
    
      if ($op == 'clone') {
        $room->sys_name .= ' (cloned)';
        $room->room_number = '';
      }
    
      $form['room_number'] = array(
        '#title' => t('Room Number'),
        '#type' => 'textfield',
        '#default_value' => isset($room->room_number)?$room->room_number : "",
        '#description' => t('Entry the Room number.'),
        '#required' => TRUE,
        '#size' => 30,
      );
    
      // Machine-readable type name.
      $form['sys_name'] = array(
        '#type' => 'machine_name',
        '#default_value' => isset($room->sys_name) ? $room->sys_name : '',
        '#maxlength' => 32,
        '#machine_name' => array(
          'exists' => 'room_get_sys_names',
          'source' => array('label'),
        ),
        '#description' => t('A unique machine-readable name for this model type. It must only contain lowercase letters, numbers, and underscores.'),
      );
    
      $form['type'] = array(
          '#title' => t('Room Type'),
          '#type' => 'textfield',
          '#default_value' => isset($room->type) ? $room->type : "",
          '#description' => t('Entry the Room type.'),
          '#required' => TRUE,
          '#size' => 60,
      );
    
    
      $form['actions'] = array('#type' => 'actions');
      $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save Room'),
        '#weight' => 40,
      );
    
      return $form;
    }
    
    /**
     * Form API submit callback for the type form.
     */
    function room_form_submit(&$form, &$form_state) {
      $room = entity_ui_form_submit_build_entity($form, $form_state);
      $room->save();
      $form_state['redirect'] = 'admin/structure/rooms';
    }
    
    
  • 以上の定義で、Entityの管理操作ができるようになります

 


DrupalのEntityを定義する簡単な例-3:バンドルの作成/拡張フィールド追加

カスタムモジュールでEntityの定義と作成

  • シリーズ記事でEntityの定義、管理を説明しました
    • DrupalのEntityを定義する簡単な例
    • DrupalのEntityを定義する簡単な例-2:エンティティ管理フォーム
  • 定義されたEntityが拡張フィールドの使用はできません
    • そのEntityのバンドル(Bundle)の定義がしなかったからです

カスタムモジュール(entity_room.zip)でEntityとそのBundleを定義し、拡張フィールドの使用ができるようにします

  • 拡張フィールドがEntityオブジェクトが作成後に必要に応じ追加することができます(柔軟性を高める)
    • カスタムモジュール(entity_room.zip)をダウンロードして、参考にしてください
  • 定義されたRoom EntityにRoomバンドル(Bundle)を指定します
    /**
     * Implements hook_entity_info().
     */
    function entity_room_entity_info()
    {
        $room_info['room'] = array(
            'label' => t('Room'),
            'controller class' => 'RoomController',
            'base table' => 'room',
            'uri callback' => 'room_uri',
            'fieldable' => TRUE,
            'entity keys' => array(
                'id' => 'rid',
                'label' => 'room_number',
            ),
            'static cache' => TRUE,
            'bundles' => array(       // バンドルの指定
                'room'=> array(         //  バンドル名: room
                    'label' => 'Room',
                    'admin' => array(
                        'path' => 'admin/structure/room/manage',  // バンドルの管理URI
                        'access arguments' => array('administer rooms'),
                    ),
                ),
            ),
            'view modes' => array(
                'full' => array(
                    'label' => t('Full Room'),
                    'custom settings' =>  FALSE,
                ),
            )
        );
    
        return $room_info;
    }
  • 管理画面(/admin/stracture/room/manage)でRoomEntityの拡張フィールドの追加ができるようになります
    • 例: Room Typeの追加
      バンドルに拡張フィールドの追加

Entity作成時に追加された拡張フィールドが現れます

  • Roomエンティティを作成(/room/add)画面に、Roomエンティティのプロパティ(room_number)と拡張フィールド(room type)が現れます
    Entity作成フォームに追加したフィールド(Room Type)が現れ
  • エンティティ表示画面(/room/[rid])にも拡張フィールドの内容が表示されます
    Entity表示画面に追加されたフィールドの内容が表示される
  • エンティティ追加、表示のコードは以下のよう
    /**
     * Implements hook_menu().
     */
    function entity_room_menu()
    {
        // 管理が面にメッセージ表示のみ
        $items['admin/structure/room/manage'] = array(
            'title' => 'Room Admin',
            'description' => 'Manage Room structure',
            'page callback' => 'room_info',
            'access arguments' => array('administer rooms'),
        );
        // 個別Room表示
        $items['room/%entity_room'] = array(
            'title callback' => 'room_page_title',
            'title arguments' => array(1),
            'page callback' => 'room_page_view',
            'page arguments' => array(1),
            'access arguments' => array('view rooms'),
            'type' => MENU_CALLBACK,
        );
        // 新規Room作成
        $items['room/add'] = array(
            'title' => t('Add Room'),
            'page callback' => 'room_add',
            'access arguments' => array('create room'),
        );
        return $items;
    }
    
    /**
     * Implements hook_permission().
     */
    function entity_room_permission()
    {
        return array(
            'administer rooms' =>  array(
                'title' => t('Administer rooms'),
                'restrict access' => TRUE,
            ),
            'create room' =>  array(
                'title' => t('Create room'),
            ),
            'view rooms' => array(
                'title' => t('View Rooms'),
            )
        );
    }
    
    /**
     * create "add room" form
     */
    function room_add() {
        $room = (object) array (
            'rid' => '',
            'type' => 'room',
            'room_number' => '',
        );
    
        return drupal_get_form('room_add_form', $room);
    }
    function room_add_form($form, &$form_state, $room) {
        $form['room_number'] = array(
            '#type' => 'textfield',
            '#title' => t('Room Number'),
            '#required' => TRUE,
        );
    
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Save'),
        );
    
        field_attach_form('room', $room, $form, $form_state);
    
        return $form;
    }
    
    function room_add_form_validate($form, &$form_state) {
        $room_submisttion = (object) $form_state['values'];
        field_attach_form_validate('room', $room_submisttion, $form, $form_state);
    }
    
    function room_add_form_submit($form, &$form_state) {
        $room_submission = (object) $form_state['values'];
        field_attach_submit('room', $room_submission, $form, $form_state);
        $room = room_save($room_submission);
        $form_state['redirect'] = "room/$room->rid";
    }
    
    function room_save(&$room) {
        return entity_get_controller('room')->save($room);
    }
    
    
    function room_info() {
        return t('Welcome to the administration page for your rooms!');
    }
    
    function room_page_title($room){
        return $room->room_number;
    }
    
    function room_page_view($room, $view_mode = 'full'){
    
        $room->content = array();
    
        // Build fields content.
        field_attach_prepare_view('room', array($room->rid => $room), $view_mode);
        entity_prepare_view('room', array($room->rid => $room));
        $room->content += field_attach_view('room', $room, $view_mode);
    
        return $room->content;
    }
    
    
    /**
     * Implements hook_field_extra_fields().
     * Field管理にRoomのプロパティ項目を追加(編集不可)
     */
    function entity_room_field_extra_fields()
    {
        $return = array();
        $return['room']['room'] = array(
            'form' => array(
                'room_number' => array(
                    'label' => t('Room Number'),
                    'description' => t('The number of the room'),
                    'weight' => 1,
                ),
            ),
        );
    
        return $return;
    }
    
    
    function room_uri( $room ){
        return array(
            'path' => 'room/' . $room->rid,
        );
    }
    
    class RoomController extends DrupalDefaultEntityController{
        public function __construct($entityType) {
            parent::__construct($entityType);
        }
    
        // Entityオブジェクト保存
        public function save($room) {
            drupal_write_record('room', $room);
            field_attach_insert('room', $room);
            return $room;
        }
    
    }
    
    /**
     * Implements hook_load().
     */
    function entity_room_load($rid = NULL, $reset = FALSE){
    
        $rids = (isset ($rid) ? array($rid) : array());
        $room = room_load_multiple($rids, $reset);
        return $room ? reset ($room) : FALSE;
    }
    
    function room_load_multiple($rids = array(), $conditions = array(), $reset = FALSE){
        return entity_load('room', $rids, $conditions, $reset);
    }
    

     

 


DrupalのEntityAPIを実装したエンティティはViewsでの検索可能になったためhook_views_dataの実装必要はない

EntityAPIを実装した場合モジュール(Views)でのエンティティ検索ができるようになります

  • モジュール(EntitAPI)をインストールし、Entityをプログラミングで定義します
    • DrupalのEntityを定義する簡単な例
  • EntityAPIがモジュール(Views)の統合機能(Integration)が提供されているため、直ちにViewsでエンティティの検索ができるようになります

うっかりしてEntityAPI実装したエンティティにhook_views_data()を実装したせいでモジュール(Entityreferecen views widget)の使用ができなくなりました

  • hook_views_data() はモジュール(Views)にカスタムテーブルの検索ができるようにする機能があります
    • 任意のカスタムテーブルをViewsで検索することができます
  • hook_views_data()の定義に「entity type」パラメーターの説明がありませんでした(本家の説明をご参考)
  • hook_views_data()実装してエンティティのデータ検索はできましたが、モジュール(Entityreferecen views widget)の使用はできません
    • Viewsの管理画面でディスプレイを追加ボタンを押すと「Entity Reference view widgetの追加」項目がありませんでした

原因:「Entity Reference view widgetの追加」項目を追加するためEntityの定義に「entity type」パラメーターが欠けていました

  • なぜ「Entity Reference view widgetの追加」項目がViewsの管理画面にないか、デバッグで調査しました
  • entityreference_view_widget.views.incの50行あたりに「Entity Reference view widgetの追加」項目の記述がありました
    • エンティティのtable/entity type の定義がなかったため、「Entity Reference view widgetの追加」項目が表示されませんでした
      hook_views_data実装時に”entity type”定義がないためentityreference views widgetsの使用はできない

修正:hook_views_data() の実装をやめたら直りました

  • hook_views_data()の実装部分を作成して、キャッシュをクリアします
  • Viewsの管理画面に「Entity Reference view widgetの追加」項目がありました

 


検索フォーム

カテゴリ別

  • laravel
  • drupal
  • javascript
  • windows
  • html
  • mysql
  • php
  • apache
  • css
  • SEO
  • video
  • wordpress
  • linux
  • python
  • Electron
  • Visual Studio Code

google ads