1

I am performing the following query, which returns me an array of matrix blocks:

$criteria = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->relatedTo = array(someCoolId, anotherCoolId);
$relatedStories = $criteria->find();

When looping through this array, I was wondering if it was possible to access the handle of the matrix block that I am currently in. Reason being is I would like to retrieve this as a string, and perform some type of work on it.

3

You can grab the handle of an element that has different types (entries, matrix) with getType()->handle for example:

$handle = $entry->getType()->handle

In your case

$criteria = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->relatedTo = array(someCoolId, anotherCoolId);
$relatedStories = $criteria->find();
foreach ($relatedStories as $block){
    $handle = $block->getType()->handle;
    switch ($handle){
        case 'foo':
            break;
    }
}

Edit:

Not sure what you mean exactly so I'll just insert some random code parts until something is correct.

// get the parent element -> the owner of that block.
$parent = $block->getOwner()

// get the field that relates both elements
$field = craft()->fields->getFieldById($block->fieldId);
$fieldHandle = $field->handle;
|improve this answer|||||
  • Now that's what's up. – Dan Zuzevich Mar 26 '18 at 15:24
  • Actually, I needed to deselect this as the selected answer. What I actually meant in my question, was, can I get the handle of the actual top level Matrix field, not the handle of every block in the matrix. – Dan Zuzevich Mar 26 '18 at 15:41
  • For example, Say I have a field called, "coolStuff" which is a matrix, and that matrix is one of the matrixes included in the array sent back to me from my query. Can I get the handle of "coolStuff" when looping through this array? – Dan Zuzevich Mar 26 '18 at 15:50

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.