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 Answer 1

2

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

1
  • Does this still work, so far as you are aware? I'm working on a migration and it involves setting the source of a currently existing field to a new category group (still only bound to one group). However, when I try to use $field->setAttribute(['source' => 'group:'.$groupUid); and save it, the field's source just sets to 'group:' and then the category group's id, and not the UID, so consequently it fails. Any thoughts on how to get that working?
    – accalton
    Commented Jun 5, 2022 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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