1

I would like to create a field / a way to relate a certain Matrix Block to another Element. Is this possible?

For example:

Entry A contains a Matrix Field matrix and has several blocks. I want to relate one of those blocks to Entry B

2

The BaseRelationField is able to relate all elements - even Matrix Blocks but it's a little bit tricky because in order to display everything properly you need to define sources but Matrix Blocks have no sources.

At first we need to make sure our Matrix Blocks have a valid source, otherwise this Javascript check messes all up

var $sources = this._getSourcesInList(this.getSourceContainer());

// No source, no party.
if ($sources.length === 0) {
    return false;
}

And nothing works So we need the following

Event::on(
    MatrixBlock::class,
    MatrixBlock::EVENT_REGISTER_SOURCES,
    function(RegisterElementSourcesEvent $event) {
        if (empty($event->sources)) {
            $event->sources[] = [
                'key'         => 'MySource',
                'label'       => 'All Matrixes',
                'defaultSort' => 'elements.id',
                'data'        => [
                    'handle' => 'matrix'
                ],
                'criteria'    => [
                    'typeId' => 21,
                    'fieldId' => 70 // <-- this is the matrix field of Entry A otherwise the values won't be populated
                ]
            ];
        }
    }
);

In order to display an identifier we need to set the title attribute to the block, otherwise all we see is an id.

Event::on(
    MatrixBlockQuery::class,
    MatrixBlockQuery::EVENT_AFTER_POPULATE_ELEMENT,
    function(PopulateElementEvent $event){
        $element = $event->element;
        if($element->getType()->handle === 'person'){ //<-- make it is the correct matrix block
            try{
                $element->title = $element->getFieldValue('firstName') . ' ' . $element->getFieldValue('lastName');
            }catch(Exception $exception){
                // whatever you need
            }
        }
    }
);

Since Matrix Blocks usually have no table attributes we need to define them as well

Event::on(
    MatrixBlock::class,
    MatrixBlock::EVENT_REGISTER_TABLE_ATTRIBUTES,
    function($event) {
        $event->tableAttributes['id'] = ['label' => 'ID'];
        $event->tableAttributes['email'] = ['label' => 'Email'];
    }
);

After that you can use the normal BaseRelationField and extend it like you are used to for custom element types

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.