8

I'm writing a plugin where I have the id of an entry, that entry has a matrix field, and I want to iterate over the blocks of the matrix field. In php. How do I do that? Pointers to good documentation for how to do this would be appreciated too.

7

So, first you want to get the entry model using your entry id. In the EntriesService there is a method called getEntryById which you can use like so:

$entry = craft()->entries->getEntryById(123);

This will return you an EntryModel which has on it all your fields. So, if you matrix field handle is called matrixFieldHandle then you would access the field contents like so:

$matrixBlocks = $entry->matrixFieldHandle;

A matrix field will return you an array of MatrixBlockModels from which you can get at everything else you need e.g.:

foreach ($matrixBlocks as $block){
  echo $block->id;
  echo $block->fieldHandle;
}

Note that to play with block types you will need to look at the MatrixService and getBlockTypeById() to do things like filter out different blocks based on their block types.

|improve this answer|||||
  • It was that $matrixBlocks = $entry->matrixFieldHandle; I was missing. Thanks!! – Marion Newlevant Aug 7 '14 at 16:16
  • No problem! Glad you got it sorted :) – Josh Angell Aug 7 '14 at 16:29

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.