Skip to content

Add field to the existing block type of Matrix field in the migration  #7123

@mmikhalko

Description

@mmikhalko

Description

When I add a new field to Matrix Block type it does not work in the migration script.

Steps to reproduce

  1. Create the new migration

  2. Add the example script below

    <?php
    
    // ...
    
    public function safeUp()
    {
        // Get the matrix field
        $exampleContents = Craft::$app->fields->getFieldByHandle("exampleContents");
    
        // Get the block types
        $blockTypes = $exampleContents->getBlockTypes();
    
        // Find the one with `justText` as the handle
        foreach ($blockTypes as $blockType) {
            if ($blockType->handle == "justText") {
                // Get all the fields
                $fields = $blockType->getFields();
    
                // Add a new field to the fields array
                array_push(
                    $fields,
    
                    // Dropdown color select
                    new \craft\fields\Dropdown([
                        "name" => "Text Color",
                        "handle" => "textColor",
                        "instructions" => "Choose one of three amazing text colors",
                        "options" => [
                            [
                                "label" => "Red",
                                "value" => "#ff0000",
                                "default" => 1,
                            ], [
                                "label" => "Green",
                                "value" => "#00ff00",
                                "default" => "",
                            ], [
                                "label" => "Blue",
                                "value" => "#0000ff",
                                "default" => "",
                            ],
                        ],
                    ])
                );
    
                // And finally set the fields and then the blocktype
                $blockType->setFields($fields);
                return (Craft::$app->matrix->saveBlockType($blockType));
            }
        }
    }

Additional info

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions