<p>I'm assuming that you're attempting to create the Matrix, with one or more blocks each containing one or more fields, from scratch? I.e. you're not simply trying to populate content into an already defined Matrix?</p>

<p>Going off of that assumption:</p>

<p>PS: Sorry, this code is not based on your code - I simply took working code from one of my other projects.</p>

<pre><code>// Create a field-group to store our Matrix in
$fieldGroup       = new FieldGroupModel();
$fieldGroup-&gt;name = 'My Field Group';
craft()-&gt;fields-&gt;saveGroup($fieldGroup);

// Create the matrix-field itself
$field          = new FieldModel();
$field-&gt;groupId = $fieldGroup-&gt;getAttribute('id');
$field-&gt;name    = 'My Matrix';
$field-&gt;handle  = 'myMatrix';
$field-&gt;type    = 'Matrix';

// Create a rich-text field which we will need later
$textField = ['name' =&gt; 'Text Field',
              'handle'       =&gt; 'label',
              'required'     =&gt; TRUE,
              'instructions' =&gt; '',
              'type'         =&gt; 'RichText',
              'typesettings' =&gt; ['configFile'            =&gt; 'Standard.json',
                                 'cleanupHtml'           =&gt; 1,
                                 'purifyHtml'            =&gt; 1,
                                 'columnType'            =&gt; 'text',          
                                 'availableAssetSources' =&gt; '',
                                 'availableTransforms'   =&gt; '']];

// Define block-types for our Matrix-field
$blockTypes = ['new1' =&gt; ['name'   =&gt; 'My text field',
                          'handle' =&gt; 'myTextField',
                          'fields' =&gt; ['new1' =&gt; $textField]];

// Assign block-types to the Matrix-field
$field-&gt;settings = ['blockTypes' =&gt; $blockTypes];

// Finish the creation of the Matrix-field by saving it
craft()-&gt;fields-&gt;saveField($field)
</code></pre>

<p>I've had to adjust the code slightly to not give you the full 125 lines of code I use (mostly due to having a LOT of different block-types with a lot of different fields) - but hopefully you can get the gist of how it's working and solve your issue based on this :)</p>

<p>PPS: It seems like your code should work fine if you only tweak the order in which you do things slightly.</p>

<ol>
<li>Create Field Group</li>
<li>Create Matrix Field</li>
<li>Define Block Fields</li>
<li>Create Block Types using defined Block Fields</li>
<li>Assign Block Types to Matrix Field</li>
<li>Save Matrix Field</li>
</ol>

CC BY-SA 3.0
2017-10-06T12:36:12.493Z
2017-10-06T12:36:12.493Z
Fuglsetrampen
<p>I am easily able to add a <code>Matrix</code>. I am also easily able to add a <code>BlockType</code> to that matrix. &rarr; I am fine so far.</p>

<p>But I have no clue what I am missing when I try to add fields to my blocks using the following example (excerpt from a custom plugin).</p>

<pre><code>/**
 * Performs any actions that should occur after the plugin is installed.
 */
public function onAfterInstall() {
    //  create new group
    $fieldGroup = new FieldGroupModel();
    $fieldGroup-&gt;name = 'Awesome Field Group';
    //  save group
    craft()-&gt;fields-&gt;saveGroup($fieldGroup);

    //  create matrix field
    $matrixField = new FieldModel();
    $matrixField-&gt;handle = 'myMatrixField';
    $matrixField-&gt;name = 'Awesome Matrix';
    $matrixField-&gt;type = 'Matrix';
    $matrixField-&gt;required = true;
    $matrixField-&gt;translatable = true;
    $matrixField-&gt;groupId = $fieldGroup-&gt;id;
    //  save matrix field
    craft()-&gt;fields-&gt;saveField($matrixField);

    //  create block type
    $blockType = new MatrixBlockTypeModel();
    $blockType-&gt;handle = 'myAwesomeBlock';
    $blockType-&gt;name = 'Awesome Block';
    $blockType-&gt;fieldId = $matrixField-&gt;id; //  also craft()-&gt;fields-&gt;getFieldByHandle('myMatrixField') possible

    //  save it
    if (craft()-&gt;matrix-&gt;saveBlockType($blockType)) {

        //  UNTIL HERE EVERYTHING WORKS PRETTY FINE.

        //  on saveField() in fields service the given field's context value is ignored because it's overwritten with "craft()-&gt;content-&gt;fieldContext"
        //  so, after saving the field's context is "global", but we want something like "matrixBlockType:&lt;id&gt;"
        //  --&gt; temporarily change this value to ensure we cann passe the block type id
        $tmp = craft()-&gt;content-&gt;fieldContext;
        craft()-&gt;content-&gt;fieldContext = 'matrixBlockType:' . $blockType-&gt;id;

        //  create field
        $field = new FieldModel();
        $field-&gt;handle = 'myTestField';
        $field-&gt;name = 'Awesome Field';
        $field-&gt;type = 'PlainText';
        $field-&gt;required = true;
        $field-&gt;translatable = true;
        //$field-&gt;context = 'matrixBlockType:' . $blockType-&gt;id;
        //  … last line is commented out because Craft ignores this value --&gt; see implementation of FieldsService::saveField();

        //  save field
        craft()-&gt;fields-&gt;saveField($field);

        //  FIELD IS ADDED TO DATABASE BUT I CAN'T SEE IT IN MY MATRIX BLOCK

        //  restore original value of "craft()-&gt;content-&gt;fieldContext"
        craft()-&gt;content-&gt;fieldContext = $tmp;
    }
}
</code></pre>

<p>I hoped this is enough to add fields to block types. But as you can see in the screenshot below my "Awesome Field" is missing. :(</p>

<p><a href="https://i.sstatic.net/JFb08.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JFb08.png" alt="field is missing for block"></a></p>

<p>When adding this field manually in Craft's admin panel the field definitions in my database look exactly the same. So, any other important step is missing here. I have no idea which one.</p>

<p>What do I have to do to add fields to matrix blocks?</p>

<p>I hope someone can lead me into the right direction. Thanks in advance. :)</p>

<plugin-development><matrix><field><block-types>
How to programmatically add fields to matrix blocks?
# How to programmatically add fields to matrix blocks?

(Asked by: username_0 on 2016-06-08)

I am easily able to add a Matrix. I am also easily able to add a BlockType to that matrix. → I am fine so far.
But I have no clue what I am missing when I try to add fields to my blocks using the following example (excerpt from a custom plugin).
/**
 * Performs any actions that should occur after the plugin is installed.
 */
public function onAfterInstall() {
    //  create new group
    $fieldGroup = new FieldGroupModel();
    $fieldGroup->name = 'Awesome Field Group';
    //  save group
    craft()->fields->saveGroup($fieldGroup);

    //  create matrix field
    $matrixField = new FieldModel();
    $matrixField->handle = 'myMatrixField';
    $matrixField->name = 'Awesome Matrix';
    $matrixField->type = 'Matrix';
    $matrixField->required = true;
    $matrixField->translatable = true;
    $matrixField->groupId = $fieldGroup->id;
    //  save matrix field
    craft()->fields->saveField($matrixField);

    //  create block type
    $blockType = new MatrixBlockTypeModel();
    $blockType->handle = 'myAwesomeBlock';
    $blockType->name = 'Awesome Block';
    $blockType->fieldId = $matrixField->id; //  also craft()->fields->getFieldByHandle('myMatrixField') possible

    //  save it
    if (craft()->matrix->saveBlockType($blockType)) {

        //  UNTIL HERE EVERYTHING WORKS PRETTY FINE.

        //  on saveField() in fields service the given field's context value is ignored because it's overwritten with "craft()->content->fieldContext"
        //  so, after saving the field's context is "global", but we want something like "matrixBlockType:"
        //  --> temporarily change this value to ensure we cann passe the block type id
        $tmp = craft()->content->fieldContext;
        craft()->content->fieldContext = 'matrixBlockType:' . $blockType->id;

        //  create field
        $field = new FieldModel();
        $field->handle = 'myTestField';
        $field->name = 'Awesome Field';
        $field->type = 'PlainText';
        $field->required = true;
        $field->translatable = true;
        //$field->context = 'matrixBlockType:' . $blockType->id;
        //  … last line is commented out because Craft ignores this value --> see implementation of FieldsService::saveField();

        //  save field
        craft()->fields->saveField($field);

        //  FIELD IS ADDED TO DATABASE BUT I CAN'T SEE IT IN MY MATRIX BLOCK

        //  restore original value of "craft()->content->fieldContext"
        craft()->content->fieldContext = $tmp;
    }
}

I hoped this is enough to add fields to block types. But as you can see in the screenshot below my "Awesome Field" is missing. :(

When adding this field manually in Craft's admin panel the field definitions in my database look exactly the same. So, any other important step is missing here. I have no idea which one.
What do I have to do to add fields to matrix blocks?
I hope someone can lead me into the right direction. Thanks in advance. :)

**Tags:** plugin-development, matrix, field, block-types


---

## 1 answers

### Answer by username_1 on 2017-10-06. Score: 3

I'm assuming that you're attempting to create the Matrix, with one or more blocks each containing one or more fields, from scratch? I.e. you're not simply trying to populate content into an already defined Matrix?
Going off of that assumption:
PS: Sorry, this code is not based on your code - I simply took working code from one of my other projects.
// Create a field-group to store our Matrix in
$fieldGroup       = new FieldGroupModel();
$fieldGroup->name = 'My Field Group';
craft()->fields->saveGroup($fieldGroup);

// Create the matrix-field itself
$field          = new FieldModel();
$field->groupId = $fieldGroup->getAttribute('id');
$field->name    = 'My Matrix';
$field->handle  = 'myMatrix';
$field->type    = 'Matrix';

// Create a rich-text field which we will need later
$textField = ['name' => 'Text Field',
              'handle'       => 'label',
              'required'     => TRUE,
              'instructions' => '',
              'type'         => 'RichText',
              'typesettings' => ['configFile'            => 'Standard.json',
                                 'cleanupHtml'           => 1,
                                 'purifyHtml'            => 1,
                                 'columnType'            => 'text',          
                                 'availableAssetSources' => '',
                                 'availableTransforms'   => '']];

// Define block-types for our Matrix-field
$blockTypes = ['new1' => ['name'   => 'My text field',
                          'handle' => 'myTextField',
                          'fields' => ['new1' => $textField]];

// Assign block-types to the Matrix-field
$field->settings = ['blockTypes' => $blockTypes];

// Finish the creation of the Matrix-field by saving it
craft()->fields->saveField($field)

I've had to adjust the code slightly to not give you the full 125 lines of code I use (mostly due to having a LOT of different block-types with a lot of different fields) - but hopefully you can get the gist of how it's working and solve your issue based on this :)
PPS: It seems like your code should work fine if you only tweak the order in which you do things slightly.

Create Field Group
Create Matrix Field
Define Block Fields
Create Block Types using defined Block Fields
Assign Block Types to Matrix Field
Save Matrix Field


---

