rendering blocks and child blocks within a theme - magento

I am currently trying to get a better understanding of how blocks work in Magento. I have looked at some of the files to get a better idea and it has helped a little, but they are a too to complex for my limited skills at the moment and I still do not have proper understanding of what is going on and how to implement them into my site. I realise they are essential to understand for working with Magento so I thought I would set up a list of things to try and achieve:
display a block (done)
display a block and child block
display a block within a magento layout
position a block on the page of a magento layout
learn the most commonly used 'type' attributes and when to use them
So far I have put together
_index_index
Namespace/Module/etc/config.xml
<frontend>
....
<layout>
<updates>
<learningblocks>
<file>Namespace/Module/childblocks.xml</file>
<file>Namespace/Module/blocks.xml</file>
</learningblocks>
</updates>
</layout>
</frontend>
Namespace/Module/controllers/IndexController.php
class Namespace_Module_IndexController
extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout('learningblocks')->renderLayout();
}
public function blocksAction()
{
$this->loadLayout('blocknode')->renderLayout();
}
}
frontend/base/default/layout/namespace/module/blocks.xml
<layout>
<blocknode>
<block type="core/text" name="blocktest" output="toHtml" >
<action method="setText">
<args>some text to display on screen</args>
</action>
</block>
</blocknode>
</layout>
The above worked as expected and displayed the string 'some text to display on screen' on a white page. But thats all i've been able to do, I cannot get child blocks to render onto the screen and I cannot display anything within a theme, let alone try and move it about within that theme
Below is one of my attempts that I cant seem to get to work. Why is this not working?
frontend/base/default/layout/namespace/module/childblocks.xml
<layout>
<abcde>
<block type="core/template" name="childblocks" output="toHtml" template="namespace/module/childblocks.phtml">
<block type="core/text" name="anyname">
<action method="setText">
<args>Some text to add to this page</args>
</action>
</block>
</block>
</abcde>
<learningblocks_index_index>
<update handle="abcde" />
</learningblocks_index_index>
</layout>
frontend/base/default/template/namespace/module/childblocks.phtml
<p>from the childblock.phtml page</p><?php $this->getChildHtml(); ?>
NB: I have changed the namespaces and module names to be more generic, in the hope it is easier to read (they wern't very well chosen names).

I know this is not a complete answer, but it may help those who have struggled with the same problem. I have not gone into great depth as I assume if your searching for an answer you will have already read THIS ARTICLE and that covers it all, I assume you have the same issue as I did i.e. a misunderstanding of what you had learnt from this tutorial.
On reading this answer please be aware I am very new to Magento and there could be some inaccuracies in here, if there are I am sure someone will correct me and edit accordingly.
Firstly this is wrong
public function indexAction()
{
$this->loadLayout('learningblocks')->renderLayout();
}
It should be this
public function indexAction()
{
$this->loadLayout()->renderLayout();
}
and then you will have to map learningblocks node in layout xml to that action module_controller_action. Doing this will display the block in the page within your theme.
So to render a child block
Add something like this in you layout.xml
<module_controller_action>
<reference name="content">
<block type="module/blockname" name="unique_name" output="toHtml" template="path/toyou/template.phtml" >
<block type="module/blockname" name="another_unique_name" output="toHtml" template="path/toyou/template.phtml" />
</block>
</reference>
</module_controller_action>
then in your template file echo out
$this->getChildHtml('another_unique_name')
If you want to remove blocks from your page use the remove node such as
<remove name="right"/>
<remove name="left"/>
This page will offer a list of attributes that can be used to be honest I found that looking through the magento files helped more than that page though

Related

Not able to change checkout/cart.phtml through layout update

I am trying to change checkout/cart.phtml through layout update in my module's layout file i.e. mymodule.xml
<layout>
<checkout_cart_index>
<reference name="checkout.cart">
<action method="setCartTemplate"><value>mymodule/checkout/cart.phtml</value></action>
</reference>
</checkout_cart_index>
</layout>
But It is not working. Any clues?
Ankita, What I'm about to write is the actual way to get what you want. While the official answer by John Hickling will work, it is not how Magento intended the main cart template to be modified.
Magento deliberately chose to use different methods for setting the cart templates, namely, setCartTemplate and setEmptyTemplate. They can be seen in Magento's own app/design/frontend/base/default/layout/checkout.xml. This was done so that two templates can be managed, each to handle their own condition. The first condition is for a cart with items, while the second condition is for a cart without items. By using the common setTemplate method, that distinction will be lost: a cart with items and a cart without items will both display the same template. This is no good.
You were so close. You were correct in trying to use the setCartTemplate method. That is what you should be using. However, you were missing one essential method call that would allow Magento to even consider using it: you forgot to include the chooseTemplate method call. Note Magento's own checkout.xml file:
<block type="checkout/cart" name="checkout.cart">
<action method="setCartTemplate"><value>checkout/cart.phtml</value></action>
<action method="setEmptyTemplate"><value>checkout/cart/noItems.phtml</value></action>
<action method="chooseTemplate"/>
Look at that last method call, chooseTemplate. If you look in app/code/core/Mage/Checkout/Block/Cart.php you will see the following method, within which those familiar setCartTemplate and setEmptyTemplate methods are called, but because they are magic methods, they are not easily searchable in Magento's source, which is problematic for a lot of people:
public function chooseTemplate()
{
$itemsCount = $this->getItemsCount() ? $this->getItemsCount() : $this->getQuote()->getItemsCount();
if ($itemsCount) {
$this->setTemplate($this->getCartTemplate());
} else {
$this->setTemplate($this->getEmptyTemplate());
}
}
You were missing that chooseTemplate method call. This is what your own layout XML file should look like:
<checkout_cart_index>
<reference name="checkout.cart">
<action method="setCartTemplate"><value>mymodule/checkout/cart.phtml</value></action>
<action method="setEmptyTemplate"><value>mymodule/checkout/noItems.phtml</value></action>
<action method="chooseTemplate"/>
</reference>
</checkout_cart_index>
I recommend you update your code if it is still under your control. This is how Magento intended the cart templates to be updated. The common setTemplate method is too destructive for this task. Granularity was Magento's intention, so updates should maintain that granularity. I also recommend you mark this as the correct answer.
The method is setTemplate not setCartTemplate, like so:
<layout>
<checkout_cart_index>
<reference name="checkout.cart">
<action method="setTemplate"><value>mymodule/checkout/cart.phtml</value></action>
</reference>
</checkout_cart_index>
</layout>

How to add JS programmatically in Magento?

I need to add a JS file conditionally and programmatically inside a block file. I tried with these codes:
if (Mage::getStoreConfig('mymodule/settings/enable')) {
$this->getLayout()->getBlock('head')->addJs('path-to-file/file1.js');
} else {
$this->getLayout()->getBlock('head')->addJs('path-to-file/file2.js');
}
However, regardless of what the setting is, none of this file is loaded. I even tried to eliminate the condition and explicitly load one file only, but it still doesn't work. What have I done wrong here?
The issue here is likely one of processing order. My guess is that your PHP code is being evaluated after the head block has been rendered. While your code is successfully updating the head block class instance, it's happening after output has been generated from that instance.
The better solution will be to add the addJs() calls in layout XML so that they will be processed prior to rendering. It would be nice if there were an ifnotconfig attribute, but for now you can use a helper.
Create a helper class with a method which returns the script path based on the config settings, then use this as the return argument.
<?php
class My_Module_Helper_Class extends Mage_Core_Helper_Abstract
{
public function getJsBasedOnConfig()
{
if (Mage::getStoreConfigFlag('mymodule/settings/enable')) {
return 'path-to-file/file1.js';
}
else {
return 'path-to-file/file2.js';
}
}
}
Then in layout XML:
<?xml version="1.0"?>
<layout>
<default>
<reference name="head">
<action method="addJs">
<file helper="classgroup/class/getJsBasedOnConfig" />
<!-- i.e. Mage::helper('module/helper')->getJsBasedOnConfig() -->
</action>
</reference>
</default>
</layout>
$this->getLayout()->getBlock('head')->addJs('path');
Its the right code, search if your path is right.
I know this was asked a long time ago, but in case somebody is looking for this, I would suggest to use this in your local.xml:
<layout>
<default>
<reference name="head">
<action ifconfig="path/to/config" method="addJs">
<script>pathto/file.js</script>
</action>
</reference>
</default>
</layout>
Of course this is for JS files located in /js/ folder. Use the appropriate method if you want to add skin_js or skin_css.
PS. Tested on CE 1.9

Magento: Referencing a custom block does not work

I'm trying to reference a block from an other custom module to add a child block via layout file but it does not work.
The first layout file contains
<catalog_product_view>
<reference name="content">
<block type="core/template" name="tabcontainer" as="tabcontainer"
template="store/tabcontainer.phtml" >
<block type="catalog/product_list_related" name="kitparts"
template="store/product/kitparts.phtml"/>
</block>
</reference>
</catalog_product_view>
and in the second one I try to reference the tabcontainer block
<catalog_product_view>
<reference name="tabcontainer">
<block type="productshippinginfo/productshipping" name="productshippinginfo"
template="productshippinginfo/productshipping.phtml" after="kitparts"/>
</reference>
</catalog_product_view>
but the productshippinginfo block is not displayed while it is definitely included in the layout (using Alan Storm's layoutviewer plugin). If I reference content it is displayed.
What is wrong? Isn't it possible to add a child to a custom block from a custom extension?
Thanks for your help!
(I'm using Magento 1.6.1.0)
[edit]
in tabcontainer.phtml I'm calling <?php echo $this->getChildHtml(); ?>
First of all: Thank you Vinai!
Adding a dependency to control the loading order of my plugins it works!
in File: app/etc/modules/Company_ContentModule.xml
<Company_ContentModule>
<active>true</active>
<codePool>local</codePool>
<depends>
<Company_ContainerModule />
</depends>
</Company_ContentModule>
So the content module is loaded after the container module.
You are close. You just need to add this to you store/tabcontainer.phtml file:
getChildHtml('productshippinginfo'); ?>
The reason blocks that are children of "content" render without a template change is that the "content" block is a core/text_list block. If you look in Mage_Core_Block_Text_List, you will see that in its rendering method (_toHtml()) it renders its children.
You could also add an empty getChildHtml() call to your tabcontainer template to achieve a similar effect as a core/text_list - in fact, if you use getChildHtml('',false,true); you'll get the sorted children (set with before="" and after="" params).
EDIT: adjusted the getChildHtml() call syntax based on OP's comment correct findings that the first param must be an empty string a/o/t a boolean.
In the second layout I think you need to provide the nesting:
<catalog_product_view>
<reference name="content">
<reference name="tabcontainer">
<block type="productshippinginfo/productshipping" name="productshippinginfo"
template="productshippinginfo/productshipping.phtml" after="kitparts"/>
</reference>
</reference>
</catalog_product_view>
In order that maganto picks that up
And because you are doing
<?php echo $this->getChildHtml(); ?>
You do not need to specifically call it by name unless you want it to appear in a particular place in your HTML output.
In order to test if your block is appearing in the page at all add output="toHtml" in you block tag.
<block type="productshippinginfo/productshipping" name="productshippinginfo"
template="productshippinginfo/productshipping.phtml" after="kitparts" output="toHtml"/>

Magento - use an alternate "price.phtml" (in addition to the existing one)

I am looking for a way to have an alternate template/catalog/product/price.phml used in one specific location, and to continue using the existing price.phtml file in all other locations.
To explain further, I need to display the regular price, and then another special price right below it - but only on the product page (for the main product being displayed). This special price is not a price that can be calculated by the catalog price rules, so I wrote my own module to do the calculation. So, everywhere that I am displaying prices I want to display with the regular ol' template/catalog/product/price.phtml file... but for the product page (the main product - not the related, upsells, etc) I want to use my own custom template/catalog/product/price-custom.phtml template file. Can anybody help?
Normally I just look in the layout xml files (for example catalog.xml) to find these types of things, but price.phtml is kinda special - it isn't that simple. And for the life of me I can't figure out if there is an easy way to swap it out conditionally on the page being viewed. I am aware that I can just update price.phtml to always print out this extra price, and then use css to hide the price everywhere, but I would rather not do that if possible.
(Also you may want to know that I only have simple products.)
This can be done in a layout XML file:
<layout>
<PRODUCT_TYPE_simple>
<reference name="product.clone_prices">
<action method="setTemplate">
<template>catalog/product/price-custom.phtml</template>
</action>
</reference>
</PRODUCT_TYPE_simple>
</layout>
Create a local.xml file, put it in app/frontend/default/YOURTEMPLATE/layout
In the local.xml file, add:
<?xml version="1.0" encoding="UTF-8"?>
<layout>
<!-- Override price template on product view page -->
<PRODUCT_TYPE_simple>
<reference name="product.info.simple">
<action method="setTemplate">
<template>catalog/product/price_product_page.phtml</template>
</action>
</reference>
</PRODUCT_TYPE_simple>
<!-- /Override price template on product view page -->
</layout>
Create a copy of catalog/product/price.phtml and put it in YOURTEMPLATE/templates/product/product_price_page.phtml
This will override the price.phtml in the template, and replace it with product_price_page.phtml
Or in your php block.
See example here :
Mage_Catalog_Block_Product_Abstract
protected $_priceBlockDefaultTemplate = 'catalog/product/price.phtml';
protected $_tierPriceDefaultTemplate = 'catalog/product/view/tierprices.phtml';
I had a similar requirement recently, where a different price template for the product page was the preferred solution.
The price block appears to be something of a special case in Magento (in the RWD theme at least), it's defined in catalog.xml as simply a block type and name within the <default/> handle:
<block type="catalog/product_price_template" name="catalog_product_price_template" />
If you look around at how some core layout files set the price template, you'll find examples like this (from bundle.xml):
<reference name="catalog_product_price_template">
<action method="addPriceBlockType">
<type>bundle</type>
<block>bundle/catalog_product_price</block>
<template>bundle/catalog/product/price.phtml</template>
</action>
</reference>
They call a method called addPriceBlockType which you can find in Mage_Catalog_Block_Product_Abstract
Based on this and after a little experimentation, I found the following solution worked for me:
<catalog_product_view>
<reference name="product.info">
<action method="addPriceBlockType">
<type>simple</type>
<block>catalog/product_price</block>
<template>catalog/product/price_product_page.phtml</template>
</action>
<action method="addPriceBlockType">
<type>configurable</type>
<block>catalog/product_price</block>
<template>catalog/product/price_product_page.phtml</template>
</action>
<!-- Set for each product type as necessary e.g. bundled, virtual etc... -->
</reference>
</catalog_product_view>
The proper way to achieve it :
<PRODUCT_TYPE_simple>
<reference name="product.info.simple">
<action method="addPriceBlockType"><type>simple</type><block>catalog/product_price</block><template>catalog/product/price-product-page.phtml</template></action>
</reference>
</PRODUCT_TYPE_simple>
<PRODUCT_TYPE_configurable>
<reference name="product.info.configurable">
<action method="addPriceBlockType"><type>configurable</type><block>catalog/product_price</block><template>catalog/product/price-product-page.phtml</template></action>
</reference>
</PRODUCT_TYPE_configurable>
...

Magento - removing wishlist link in 1.4.2?

Previously in Magento, the wishlist link was added using the following (in wishlist.xml):
<action method="addWishlistLink"></action>
And you could override that and remove it using the following (in your local.xml):
<remove name="wishlist_link"/>
However, in the newest Magento, 1.4.2, they've changed how the wishlist link is added to the following:
<action method="addLinkBlock"><blockName>wishlist_link</blockName></action>
Anyone know how to remove the wishlist link now they’ve changed how it’s added?
It appears there's no publicly available way to reliably remove the wishlist link block from the layout. (you can skip to the end for a workaround)
The addLinkBlock assumes the presence of the block that's been passed, so using remove in the way you describe results in a fatal error being thrown
Fatal error: Call to a member function getPosition() on a non-object in /Users/alanstorm/Sites/magento1point4.2.dev/app/code/core/Mage/Page/Block/Template/Links.php on line 112
Here's the core code that causes that error
app/code/core/Mage/Page/Block/Template/Links.php
public function addLinkBlock($blockName)
{
$block = $this->getLayout()->getBlock($blockName);
$this->_links[$this->_getNewPosition((int)$block->getPosition())] = $block;
return $this;
}
This method assumes its going to be able to pull out a block by whatever name gets passed, so we can't just remove the wishlist_link block as we could in previous versions.
The only mechanism for removing a link appears to be the following method on the same block class
app/code/core/Mage/Page/Block/Template/Links.php
public function removeLinkByUrl($url)
{
foreach ($this->_links as $k => $v) {
if ($v->getUrl() == $url) {
unset($this->_links[$k]);
}
}
return $this;
}
However, this is done using string comparison, and there's no reliable way (that I know of) to generate a URL Object from a layout file, cast it as a string, and pass it into the method (this would be required, as there are numerous configuration settings that can change what the final string URL will be). That makes this method not helpful for our needs.
So, what we can do it modify the existing wishlist_link block to use a blank or non-existant template. This way the block still renders, but it renders as an empty string. The end result is we avoid the fatal error mentioned above, but still manage to remove the link from our selected pages.
The following would remove the link from all the pages using the default handle.
<!-- file: local.xml -->
<layout>
<default>
<reference name="wishlist_link">
<action method="setTemplate"><template>blank-link.phtml</template></action>
</reference>
</default>
</layout>
In your local.xml file,
<?xml version="1.0"?>
<layout version="0.1.0">
<default>
<reference name="root">
<reference name="top.links">
<!-- Remove wishlist link in magento 1.4.x and newer -->
<remove name="wishlist_link"/>
</reference>
</reference>
</default>
</layout>
You can remove the wishlist link from the admin panel System > Configuration > Wishlist > Enabled = "No"
Add the following to your local.xml file.
<reference name="top.links">
<remove name="wishlist_link"/>
</reference>
This works! I have removed Wishlink from Toplinks and wanted to add it back into another block but that doesn't seem possible when you remove it in this way. Sadly.
I know I'm years late here, but for all of those people who are still looking for answers to this.
I have a way to work around this issue that is only a bit of extra work but it's not hacky and it gives you FULL control of your top.links block.
Simply unset the top.links block and re-create it, it will be empty (no more wishlist_link block) and all you have to do is add whichever links you want inside of it! (Do all of this in your theme/layout/local.xml file of course).
<layout version="0.1.0">
<default>
<!-- HEADER -->
<reference name="header">
<!-- Unsetting the already existing top links block -->
<action method="unsetChild">
<name>topLinks</name>
</action>
<!-- Re-creating a new top links block -->
<block type="page/template_links" name="top.links" as="topLinks">
<!-- EXAMPLE: Account Dashboard Link -->
<action method="addLink" translate="label title" module="catalog">
<label>Account Dashboard</label>
<url helper="customer/getAccountUrl"/>
<title>Account Dashboard</title>
</action>
<!-- You can add any other links that you want -->
</block>
</reference>
</default>
</layout>
Also remember that for some links like Sign In and Log Out you will need to reference your top.links block inside the appropriate <customer_logged_out> and <customer_logged_in> handles instead of inside of <default> as a guide for this you can look at Magento's customer.xml file.
IMPORTANT: If there are any modules included in your project that add links to the top.links block, those links won't show up because local.xml is processed last, so just keep that in mind when using this method :)
I am a Certified Magento Front End Developer with over 3 years of experience and I have overcome LOTS of layout XML headaches to the point where we became best friends.

Resources