Programatically create a Matrix field I'm developing a plugin which requires certain sections and fields to exist so I'm currently creating them in the onAfterInstall() method of the plugin.

I can create individual fields, sections, entry types and even a Matrix field + block type fine. I'm having trouble with creating the Matrix sub-field and attaching that field to the Matrix block type.

I have created the matrix field:

$field = new FieldModel();
$field-&gt;groupId      = $group-&gt;id;
$field-&gt;name         = Craft::t('Field Name');
$field-&gt;handle       = 'handleName';
$field-&gt;translatable = false;
$field-&gt;type         = 'Matrix';
craft()-&gt;fields-&gt;saveField($fieldContentRSS);


And this is the block type:

$blockType = new MatrixBlockTypeModel();
$blockType-&gt;fieldId = $field-&gt;id;
$blockType-&gt;name = Craft::t('Block Name');
$blockType-&gt;handle = 'handleName';
craft()-&gt;matrix-&gt;saveBlockType($blockType);


I know that I will need to create a field/set of fields for this block type. Is this exactly the same as the new field above? How do I then attach these fields to the block type?
Creating the field/block types manually is only part of the equation - you would also need to create the new content table for your Matrix field.

All you need to do is assign all of your block types and their sub-fields’ settings to $field-&gt;settings before calling saveField():

$field = new FieldModel();
$field-&gt;groupId      = 1;
$field-&gt;name         = Craft::t('Field Name');
$field-&gt;handle       = 'handleName';
$field-&gt;translatable = false;
$field-&gt;type         = 'Matrix';

$field-&gt;settings = array(
    'blockTypes' =&gt; array(
        'new1' =&gt; array(
            'name' =&gt; 'My Block Type 1',
            'handle' =&gt; 'myBlockType1',
            'fields' =&gt; array(
                'new1' =&gt; array(
                    'name' =&gt; 'My Sub-Field 1',
                    'handle' =&gt; 'mySubField1',
                    'required' =&gt; true,
                    'translatable' =&gt; false,
                    'type' =&gt; 'PlainText',
                    'typesettings' =&gt; array(
                        'multiline' =&gt; false,
                    )
                ),
                'new2' =&gt; array(
                    'name' =&gt; 'My Sub-Field 2',
                    'handle' =&gt; 'mySubField2',
                    'required' =&gt; false,
                    'translatable' =&gt; false,
                    'type' =&gt; 'PlainText',
                    'typesettings' =&gt; array(
                        'multiline' =&gt; true,
                    )
                ),
            )
        )
    )
);

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