templeton / craft-category-groups-field

一个用于选择分类组的 Craft CMS 字段类型

2.1.0 2023-12-21 09:07 UTC

This package is auto-updated.

Last update: 2024-09-21 10:42:32 UTC


README

Craft CMS 的分类组字段类型。

用法

单选设置

单选字段设置控制分类组字段的行为。当此设置禁用时,字段将类似于元素编辑页面上的典型多选字段,在模板中访问字段将提供分类组集合。当单选启用时,字段将类似于元素编辑页面上的下拉字段,在模板中访问字段将提供分类组模型。

更改此设置后,字段数据不会立即更改,以防设置被意外更改;数据仅在实际上保存其元素时才会被覆盖。然而,当单选启用时,元素编辑页面和模板将把第一个(按字母顺序)选择的分类组视为字段唯一的分类组。

新分类组字段将默认为多组选择。如果您希望将单选作为默认值,请将以下内容复制到 config/category-groups-field.php

<?php

return [
    'singleSelectionDefault' => true,
];

模板示例:单选禁用

此示例使用分类组集合的 all() 方法遍历集合的组。

{% if entry.categoryGroupsField %}
    <p>Multi-selection category groups field:</p>
        {% for group in entry.categoryGroupsField.all() %}
            <p>{{ group.name }}</p>
        {% endfor %}
    </p>
{% else %}
    <p>No category groups selected :(</p>
{% endif %}

在模板中可以以类似于典型 Craft 元素查询执行方法的方式访问多选分类组字段的数据,包括方法 all()one()nth()count()ids()

它还可以用于获取所选分类组的类别,使用 categories() 方法返回 Craft 类别查询

{% if entry.categoryGroupsField %}
    {% for category in entry.categoryGroupsField.categories().all() %}
        <p>{{ category.title }}</p>
    {% endfor %}
{% endif %}

使用 categories() 后,如果您想设置任何其他类别查询参数,请小心不要设置 groupId,因为它将覆盖字段中选择的组的 ID。如果您需要设置额外的分类组 ID,可以将包含类别查询参数的哈希传递给 categories(),其中包含的组 ID 将与字段中选择的 ID 合并

{% if entry.categoryGroupsField %}
    {# Gets the categories from category groups with IDs 1, 2 and 3, as well as the category groups selected in the field #}
    {% for category in entry.categoryGroupsField.categories({groupId: [1, 2, 3]}).all() %}
        <p>{{ category.title }}</p>
    {% endfor %}
{% endif %}

模板示例:单选启用

{% if entry.categoryGroupField %}
    <p>Single selection category group field: {{ entry.categoryGroupField.name }}</p>
{% else %}
    <p>No category group selected :(</p>
{% endif %}

允许的组设置

选择您的字段可以从中选择的分类组,或让它从所有组中选择。

要求

分类组字段需要 Craft CMS 4.5.0 或更高版本。

安装

分类组字段可以从 Craft 插件商店 或使用 Composer 安装。

Craft 插件商店

打开您项目的控制面板,转到插件商店,搜索分类组字段并点击安装。

Composer

打开您的终端,导航到您项目的根目录并运行以下命令

composer require ttempleton/craft-category-groups-field

然后打开您项目的控制面板,转到设置→插件,找到分类组字段并点击安装。

支持

如果您发现分类组字段存在问题,请通过在 GitHub 上 提交问题 告诉我。