Cms: Remove the field from existing Field Layout of the Entry Type Section in the migration

Created on 30 Nov 2020  路  1Comment  路  Source: craftcms/cms

Description

When I try to remove the field from existing Field Layout of the Entry Type Section it does not remove in the end

Steps to reproduce

  1. Create the new migration
  2. Add the example script below
 public function safeUp() {
    $section = Craft::$app->sections->getSectionByHandle('mySection');
    $types = $section->getEntryTypes();
    $entryType = $types[0];
    $fields = $entryType->getFields();

    foreach ($fields as $key => $value) {
        if ($value->handle == 'someField') {
            unset($fields[$key]);
        }
    }

    $fieldLayout = $entryType->getFieldLayout();
    $tab = $fieldLayout->getTabs()[0];

    $tab->setFields($fields);
    $fieldLayout->setTabs([$tab]);
    $entryType->setFieldLayout($fieldLayout);

    $res = $entryType->setFields($fields);

    $resSectionEntrytype = Craft::$app->sections->saveEntryType($entryType);
    $resSection = Craft::$app->sections->saveSection($section);

}

Additional info

  • Craft version: 3.5.14
  • PHP version: 7.3.15
  • Database driver & version: MySQL 5.6.39
  • Plugins & versions:
expected behavior

Most helpful comment

As of Craft 3.5, you have to remove the field from the tab鈥檚 $elements array.

use craft\fieldlayoutelements\CustomField;

public function safeUp() {
    $section = Craft::$app->sections->getSectionByHandle('mySection');
    $types = $section->getEntryTypes();
    $entryType = $types[0];
    $fieldLayout = $entryType->getFieldLayout();
    $tab = $fieldLayout->getTabs()[0];

    foreach ($tab->elements as $i => $element) {
        if ($element instanceof CustomField && $element->getField()->handle === 'someField') {
            unset($tab->elements[$i]);
            break;
        }
    }

    Craft::$app->sections->saveEntryType($entryType);
}

>All comments

As of Craft 3.5, you have to remove the field from the tab鈥檚 $elements array.

use craft\fieldlayoutelements\CustomField;

public function safeUp() {
    $section = Craft::$app->sections->getSectionByHandle('mySection');
    $types = $section->getEntryTypes();
    $entryType = $types[0];
    $fieldLayout = $entryType->getFieldLayout();
    $tab = $fieldLayout->getTabs()[0];

    foreach ($tab->elements as $i => $element) {
        if ($element instanceof CustomField && $element->getField()->handle === 'someField') {
            unset($tab->elements[$i]);
            break;
        }
    }

    Craft::$app->sections->saveEntryType($entryType);
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

brandonkelly picture brandonkelly  路  3Comments

richhayler picture richhayler  路  3Comments

darylknight picture darylknight  路  3Comments

lukebailey picture lukebailey  路  3Comments

davist11 picture davist11  路  3Comments