July 14, 2020

cm-mini

Thinking Magento

Magento - Using Conditional Attributes For Display

In Magento you have all these great features in terms of adding attributes to your products, but utilising them in a far more constructive way than just "display on product page" is a little bit harder, but worth the learning curve. With some basic php know how you can turn those static stuffy attributes into extremely useful events on the product page. Today we are going to demonstrate a simple, yet effective use of this by showing you how to change an "add to cart" button into a "Pre Order Item" button.

To start with create your attribute in the backend. An example setup would be;

  • Attribute Code: pre-order
  • Scope: Shop View
  • Type: Dropdown
  • Unique Value: No
  • Required: No
  • Validation:None
  • Apply To: All Products
  • Frontend Attributes: All set to no

For the dropdown options

  • Pre Order Available For This Item

Save

Go to Manage Attribute Sets and add pre-order to the various set names.

Now time for the code:


<?php if($_item->isSaleable()): ?>
<?php if ($_product->getData('pre-order')): ?>
getResource()->getAttribute('pre-order')->getFrontend()->getValue($_product); ?>
<?php if ($preorder=="Pre Order Available For This Item"): ?>
<button type="button" class="form-button" onclick="setLocation('getAddToCartUrl($_product) ?>')"><span>__('Pre Order Item') ?>

<button type="button" class="form-button" onclick="setLocation('getAddToCartUrl($_product) ?>')"><span>__('Add To Cart') ?>


<button type="button" class="form-button" onclick="setLocation('getAddToCartUrl($_product) ?>')"><span><?php echo $this->__('Add To Cart') ?></span></button>
<?php endif; ?>
<?php endif; ?>

This code can now be used to replace the current add to cart button, from the if saleable statement on both the list.phtml and the view.phtml files in the frontend catalog template folder.