4

I'm trying to setup some Global fields in a migration.

I'm using the SuperTable Field from verbb which is similar to a matrix field.

I'd like to add several rows during migration but can't seem to get the combination right in order to set the field values. Can someone help me out, what I've got so far is the following:

   $globalSet = Craft::$app->globals->getSetByHandle("myGlobals");  

   $globalSet->setFieldValues([
            'siteName' => "The Website",
            'siteCustom' => [
                'new1' => [
                    'type' => 'superTableBlockType',
                    'fields' => [
                        'firstField' => "some value",
                        'secondField' => "some other value"
                    ]
                ]
            ]
        ]
   );

   Craft::$app->globals->saveSet($globalSet);

1 Answer 1

2

So it looks like you must get the correct block type in order for this to create new rows in the SuperTable.

First get the block type using the SuperTable service:

       //you'll need to reference this in your code
       use verbb\supertable\SuperTable;

       $field = Craft::$app->getFields()->getFieldByHandle('siteCustom');
       $blockType = SuperTable::$plugin->service->getBlockTypesByFieldId($field->id)[0];

Then use that same blockType id to set the type field:

       $globalSet = Craft::$app->globals->getSetByHandle("myGlobals");  

       $globalSet->setFieldValues([
              'siteName' => "The Website",
              'siteCustom' => [
                   'new1' => [
                          'type' => $blockType->id,
                          'fields' => [
                              'firstField' => "some value",
                              'secondField' => "some other value"
                           ]
                   ]
               ]
       ]);

       Craft::$app->globals->saveSet($globalSet);

If you need to add more than one value to siteCustom you can do so with the same syntax, just make sure you increment the number after new each time (so new2, new3, and so on).

1
  • That answer aged pretty well. 👍 Still works for Craft CMS 4, though I had to replace SuperTable::$plugin->service with SuperTable::$plugin->getService(). And in my special case I had to pass in a context to Craft::$app->getFields()->getFieldByHandle('fieldHandle', false) (I just passed false) because I am dealing with a SuperTable field within a MatrixBlock instead of a standalone SuperTable field. Works like a charm! Thanks.
    – Arvid
    Commented May 16, 2023 at 14:04

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.