1

i am trying to create a super table field programmatically. this is the code i tried.

i see super table field in field list but i can see fields inside of super table.

how can i do this?

    //create super table field itself
    $superTable = new SuperTableField([
        'name' => 'supertablefield',
        'handle' => 'supertablefield',
        'groupId' => 1
    ]);
    Craft::$app->getFields()->saveField($superTable);
    //field inside super table
    $field = new \craft\fields\PlainText([
        "name" => 'textfield',
        "handle" => 'textfield',
        "translationMethod" => "site",
        "multiline" => 0,
    ]);
   //create and set block type
    $blockModel = new SuperTableBlockTypeModel();
    $blockModel->fieldId = $superTable->id;
    $blockModel->uid = StringHelper::UUID();
    $blockModel->setFields([$field]);

    $superTable->setBlockTypes([$blockModel]);
    SuperTable::$plugin->service->saveBlockType($blockModel);
2
+100

Not sure if this is the answer without playing, but try saving the plain text field before adding it to the super table:

    // Create the super table field

    $superTable = new SuperTableField([
        'name' => 'supertablefield',
        'handle' => 'supertablefield',
        'groupId' => 1
    ]);

    Craft::$app->getFields()->saveField($superTable);


    // Create plain text field

    $field = new \craft\fields\PlainText([
        "name" => 'textfield',
        "handle" => 'textfield',
        "translationMethod" => "site",
        "multiline" => 0,
    ]);


    // Save the plain text field

    Craft::$app->getFields()->saveField($field);


    // Retrieve the plain text field 

    $plainTextField = Craft::$app->fields->getFieldByHandle("textfield")


    // Create and set the block

    $blockModel = new SuperTableBlockTypeModel();
    $blockModel->fieldId = $superTable->id;
    $blockModel->uid = StringHelper::UUID();
    $blockModel->setFields([$plainTextField]);
    $superTable->setBlockTypes([$blockModel]);
    SuperTable::$plugin->service->saveBlockType($blockModel);
| improve this answer | |
  • Not sure if you could do $plainTextField = Craft::$app->getFields()->saveField($field) to make it cleaner. – user3788089 Jun 2 at 17:19
  • thanks! it works. i don't know why but when i create matrix there is no need to save field before setting field in block type -although this is another topic- – user9975 Jun 2 at 17:42

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.