1

I have a simple plugin which reads in a CSV file, and based on the first row of data will create a new field group, and then create fields within that group. The first time I run it everything goes well. The group is created, and the fields are also all created. However, if I re-run it with a new field it will delete the field group. Does anyone have any thoughts on why this is? This is the code, below:

This block checks if the desired group exists, and if not creates it:

protected function getFieldGroup($groupName) {
    $groups = Craft::$app->fields->getAllGroups();
    foreach ($groups as $group) {
        if ($group->name == $groupName) {
            return $group->id;
        }
    }

    $group = new FieldGroup();
    $group->name = $groupName;
    Craft::$app->getFields()->saveGroup($group);

    return $group->id;
}

The following is the code to then create the fields:

$fieldsService = Craft::$app->getFields();
$groupId = $this->getFieldGroup('My Group');
foreach ($fieldNames as $fieldName) {
    $fieldHandle = lcfirst(str_replace(' ', '', $fieldName));
    $fieldHandle = str_replace('#of', 'numOf', $fieldHandle);

    $field = $fieldsService->createField([
        'type'    => 'craft\fields\PlainText',
        'name'    => $fieldName,
        'handle'  => $fieldHandle,
        'groupId' => $groupId,
    ]);

    $fieldsService->saveField($field);
}

The point at which the field group is deleted is on running the $fieldsService->saveField($field); command.

So, just to reiterate: The first time this runs there are no issues. Group and fields are created. Running it a second time, if a new field is being added, the group gets deleted. This results in all the fields created for that group being assigned "NULL" in their groupId in the database, which causes errors.

Any help would be appreciated, thank you!

  • 1
    Craft 3.1? If so chances are high you need to process your changes via project config. Otherwise the next time you save the group Craft tries to sync it from project config since those changes aren't applied yet (if it's the same request and you iterate your rows) it will sync your DB with the config and delete your newly created group since it's not in the config yet – Robin Schambach Mar 22 at 20:01
  • The site does not make use of the project config (it is not enabled in the general.php file). Is this still a possible cause, however? – aylnon Mar 25 at 13:22
  • It always uses the project config. This setting just outputs it in a yaml file but you can't disable the project config in Craft 3.1 – Robin Schambach Mar 25 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.