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:<id>"
// --> 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. :)
