How to Get Attributes from a Block

Permalink
I'd like to make use of the attributes of a block that I have created using JordanLev's excellent Designer Content add-on. Basically, it's a block with all sorts of stuff in it. To simplify things, let's pretend there's a dropdown list in it with 'special' or 'standard' as the options.
$myBlock = Block::getByName('My Custom Block');
//
// code to get an attribute from my custom block goes here
// $myBlockAttribute = ??? what do I put here ???
//
if ($myBlockAttribute == "special"){
  echo "This block is special:<br />";
  $myBlock->display();
}
else {
  echo "This block isn't special enough to display<br />";
}

Now, I know I can control the display of this custom block with the view.php file, but I would like to be able to re-use the same blocks in different places and control their display according to where the blocks are being used. Accessing the attributes would give me a whole range of flexibility for what I can do with those blocks.

My question is... How do I access the attributes of a block (especially a block created with the Designer Content add-on)?

Many thanks,

Jules

juliandale
 
jordanlev replied on at Permalink Reply
jordanlev
You need to add a function to the controller of the block that gives you the value you want. For example, let's say you have a dropdown field in your block for choosing a certain attribute, and let's say the value of the dropdown field is called "field_5_dropdown_value" (you'll have to look in your block's db.xml file to find out the actual field name in your case). Add this to your block's controller:
public function getMySpecialAttribute() {
    return $this->field_5_dropdown_value;
}


Then your template code would be this:
$myBlock = Block::getByName('My Custom Block');
if ($myBlock->getMySpecialAttribute() == "special"){
  echo "This block is special:<br />";
  $myBlock->display();
}
else {
  echo "This block isn't special enough to display<br />";
}
juliandale replied on at Permalink Reply
juliandale
Thanks for your reply Jordan, but I got this error message:

Fatal error: Call to undefined method Block::getMySpecialAttribute()

I've added this function to my custom block's controller.php file:
public function getMySpecialAttribute() {
  return $this->field_5_select_value;
}


Any ideas?
jordanlev replied on at Permalink Best Answer Reply
jordanlev
Try changing this line of the code I provided:
if ($myBlock->getMySpecialAttribute() == "special") {

...to this:
if ($myBlock->getInstance()->getMySpecialAttribute() == "special") {
juliandale replied on at Permalink Reply
juliandale
Thanks Jordan, it worked perfectly :-)