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 ?

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

1 Answer 1

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 and acknowledge you have read our privacy policy.

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