1

I am writing a plugin that sets up Craft in a particular way and have created a category field, but can't figure out how to assign a category group to the field, I have the following:

 protected function createCategoriesField() {

        // Get the field group
        $group = (new \craft\db\Query())
            ->select("id")
            ->from("fieldgroups")
            ->where(["name" => "common"])
            ->one();

        // Get the category group
        $catGroup = Craft::$app->categories->getGroupByHandle("categories");


        // Initialize the field
        $field = new \craft\fields\Categories([
            "groupId" => $group["id"],
            "name" => "Categories",
            "handle" => "categories",
            "selectionLabel" => "Select categories",
            "sources" => $catGroup
        ]);

        // Save the field
        return (Craft::$app->getFields()->saveField($field));
    }

It seems sources is the correct setting, but it accepts 'source keys' which I'm unfamiliar with 🤔

1

Figured it out, the format it expects is 'source' => 'group: <group UID>'

So...

    protected function createCategoriesField() {
        // Get the group
        $group = (new \craft\db\Query())
            ->select("id")
            ->from("fieldgroups")
            ->where(["name" => "common"])
            ->one();

        // Get the category group UID
        $catGroup = Craft::$app->categories->getGroupByHandle("categories")->uid;

        // Initialize the field
        $field = new \craft\fields\Categories([
            "groupId" => $group["id"],
            "name" => "Categories",
            "handle" => "categories",
            "selectionLabel" => "Select categories",
            "source" => "group:" . $catGroup
        ]);

        // Save the field
        return (Craft::$app->getFields()->saveField($field));
    }

This was, and is, going to be a big help with migrations -> https://github.com/markhuot/craftql/blob/master/src/Console/ToolsController.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.