0

I'm writing an if statement in which a button needs to show if the cart is empty. For this button I need to get the form key of the product for the data-url So something like this:

<a href="#" data-url="checkout/cart/add/product/59/form_key/<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>/" class="btn btn-success">Order</a>

As mentioned above I need to wrap this button in an if statement, so something like this:

 <?php
    $_helper = Mage::helper('checkout/cart');
    if (1 > $_helper->getItemsCount()){
        echo '<a href="#" data-url="checkout/cart/add/product/59/form_key/<?php echo Mage::getSingleton(\'core/session\')->getFormKey(); ?>/" class="btn btn-success">Order</a>';
    }
    else{
        '<p>hello</p>';
    }
 ?>

But obviously I can't have php echo within echo. Can anybody point me in the right direction of how to do this?

1
  • Here is where you need to read into concatenation. An example of this would be <?php echo('string here '.$string); ?> Commented Oct 3, 2017 at 13:17

3 Answers 3

4

You don't put PHP inside HTML inside PHP. Since you're already in the context of PHP code, just concatenate the values you want to the output:

echo '<a href="#" data-url="checkout/cart/add/product/59/form_key/' . Mage::getSingleton('core/session')->getFormKey() . '" class="btn btn-success">Order</a>';

The resulting output is always just a string. You can simply build that string with whatever values you have.

Sign up to request clarification or add additional context in comments.

1 Comment

Instead of using concationation, there is a good practise to use spritf function which makes codes more readeable. So, echo sprintf( '<a href="#" data-url="checkout/cart/add/product/59/form_key/%s" class="btn btn-success">Order</a>', Mage::getSingleton('core/session')->getFormKey());
1

You can just use string concatenation:

echo '<a href="#" data-url=".../' . Mage::getSingleton(...) . '"' ...

Comments

0

Simply don't open PHP up again. You can terminate the HTML interpretation inside an echo.

Your code should look like this:

<?php
    $_helper = Mage::helper('checkout/cart');
    if (1 > $_helper->getItemsCount()) {
    echo '<a href="#" data-url="checkout/cart/add/product/59/form_key/'.Mage::getSingleton(\'core/session\')->getFormKey().'/" class="btn btn-success">Order</a>';
    }
    else {
        '<p>hello</p>';
    }
    ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.