Search code examples
phpif-statementmagentoattributesintersection

Magento if attribute value is x or y then show custom block


On view.phtml, i am trying to get the custom block "console" to display if the value of the attribute platform is either "xbox", "playstation" or "nintendo".

I got the code working for xbox, but how can i solve it so that the block is displayed it the value instead is playstation or nintendo?

Br, Tobias

<?php if ($_product->getAttributeText('platform') == "xbox"): ?>
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml() ?><?php endif; ?>

Solution

  • Do you mean you want the same block for any of the consoles? I suggest a switch statement

    Replace the if statement you wrote with this:

    switch($_product->getAttributeText('platform')){
      case "xbox" :
      case "nintendo" :
      case "playstation" :
        echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml();
        break;
      default :
        //here you can put a default other block or show nothing or whatever you want to do if the product is not a console
    }
    

    Now you can add more consoles by adding more case "other console" : statements.

    There are other ways. You could create an array of all consoles from the attribute values and then use inArray(); - that might be better for the general case if your client adds more consoles to the attribute via the Magento admin.

    **EDITED ** following the comment below

    If the attribute 'platform' is multiselect then $_product->getAttributeText('platform') will be string if one item is selected but if there are multiple items selected it will be an array. So you need to handle a single variable that can be string or array. Here we will convert string to array and use PHP's handy array_intersect() function.

    I suggest:

    $platformSelection = $_product->getAttributeText('platform');
    if (is_string($platformSelection))
    {
        //make it an array
        $platformSelection = array($platformSelection); //type casting of a sort
    }
    
    //$platformSelection is now an array so:
    
    //somehow know what the names of the consoles are:
    $consoles = array('xbox','nintendo','playstation');
    
    if(array_intersect($consoles,$platformSelection)===array())
    {
        //then there are no consoles selected
        //here you can put a default other block or show nothing or whatever you want to do if the product is not a console
    }
    else
    {
        //there are consoles selected
        echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml();
    }
    

    Note that the array_intersect() function compares the array elements strictly that is === so it is case sensitive and the function returns an empty array array() if there is no intersection.