LoginSignup
0
0

baserCMS ver.5系でカスタムコンテンツをトップページなどに表示する

Posted at

baserCMSの5系の新機能 「カスタムコンテンツ」

baserCMSの5系になってから新たにできた機能 「カスタムコンテンツ」は、
自分で好きな入力項目などが作成でき、マスター・テーブルと紐づけて自由にコンテンツが設計できる強力な機能です

image.png
また、自分で作ったカスタムコンテンツをコンテンツツリーに追加することで、好きなURLを簡単に当てることができます。

image.png

このカスタムコンテンツを使った一番良く使いそうなコンテンツとして、「カスタムフィールド+ブログ」のようなものを作成しようと考えている方も多いかと思います。
(baserCMSも4系にはCuCustomField(カスタムフィールド)プラグインが存在していましたが、5系ではカスタムコンテンツに統合されてしまっています。)

ブログ的な使用の仕方をする場合、トップページなどに最新記事を何件か表示する事があると思います。
ブログの場合は

$this->BcBaser->blogPosts({ブログname}, 5);

などで簡単に一覧表示を呼び出すことができました。

ところが、現在baserCMS 5系のカスタムコンテンツに
$this->BcBaser->blogPosts( $contentsName , $num , [$options] );
のような機能を持つメソッドは存在しません。

そこで、ちょっと難しいですが、使用テーマ専用のHelperなどを作成し、
テーマ専用で呼び出しメソッドを作るやり方に付いて一例を説明したいと思います。

まず、使用テーマ専用のHelperなどを作成します。
(例 plugins/テーマ名/src/View/Helper/ThemeHelper.phpを作成)
その中に下記の様なメソッドを作成します。

    /**
     * カスタムエントリーの一覧を取得する
     *
     * @param entity or int $customContent
     * @param int $num
     * @param array $options
     * @return mixed
     *
     * @checked
     * @noTodo
     * @unitTest
     */
    public function getCustomEntries($customContent, int $num = 5, array $options = [])
    {
        // $customContentが entityId だった場合
    	if (is_integer($customContent)) {
    		$customContent = $this->getService(CustomContentsServiceInterface::class)->get($customContent, [
    			'status' => 'publish'
    		]);
    	}
    	$this->entriesService = $this->getService(CustomEntriesServiceInterface::class);
    	$this->entriesService->setup($customContent->custom_table_id);
    	$params = array_merge([
    		'contain' => ['CustomTables' => ['CustomContents' => ['Contents']]],
    		'status' => 'publish',
    		'order' => $customContent->list_order,
    		'direction' => $customContent->list_direction,
    		'limit' => $num
    	], $options);
    	return $this->entriesService->getIndex($params)->toList();
    }

このような感じのメソッドを作成すると、
テーマファイル内で

$entries = $this->Theme->getCustomEntries(1, 5);

ID:1ので呼び出すことができ、
$entriesをループで回して表示できるように組込を行うことで対応は可能です。
ちなみにこのIDは「custom_contents」テーブルのidで、
「カスタムコンテンツ設定編集」画面のurlの末尾の数値と同じです。

/baser/admin/bc-custom-content/custom_contents/edit/1

この場合は idは1となります。

注意
ヘルパー内で下記読み込みが必須です。

use BcCustomContent\Service\CustomContentsServiceInterface;
use BcCustomContent\Service\CustomEntriesServiceInterface;

普段テーマ専用のHelperを作成していないとちょっと難しいかもしれませんが、
ぜひともトライしてみてください。

0
0
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
0
0