1

The following code is in a migration. It runs fine and there are no errors and prints SAVED, but nothing is saved in the globalsets database table.

All my other content migrations run fine so it is not a DB issue.

    $globalConfig = [
      "type" => \craft\elements\GlobalSet::class,
      "settings" => [
        "name" => "Meta",
        "handle" => "meta"
      ],
    ];

    $element = Craft::$app->getElements()->createElement($globalConfig);

    if (Craft::$app->getElements()->saveElement($element)) {
        print "SAVED";
    }

Why is this not saving ?

  • After you call saveElement(), does $element->getErrors() return anything? – Brad Bell Sep 25 at 19:41
  • @BradBell getErrors is just an empty array. Do I also need to save a field layout first ? – 32423hjh32423 Sep 26 at 7:25
1

Answer:

So I looked in the craft core to see how the CP does it. Turns out we have to use this

$gs = new \craft\elements\GlobalSet();
$gs->name = "Meta";
$gs->handle = "meta";

Craft::$app->getGlobals()->saveSet($gs);

Hope this helps someone.

Craft core reference

https://github.com/craftcms/cms/blob/develop/src/controllers/GlobalsController.php#L55-L96

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.