The best way to go about would be to have a custom module for that. A good tutorial on that can be found here.
Now for the module itself. We'll need a Block class for some business logic and a template file. But first let's create the config.xml
.
Swap out [namespace]
and [module]
for some actual names. Be careful, they're case sensitive.
<?xml version="1.0"?>
<config>
<modules>
<[Namespace]_[Module]>
<version>0.1.0</version>
</[Namespace]_[Module]>
</modules>
<global>
<blocks>
<[namespace]_[module]>
<class>[Namespace]_[Module]_Block</class>
</[namespace]_[module]>
</blocks>
</global>
</config>
Now for the block class, create a directory Block
in your module folder with a file called Form.php
class [Namespace]_[Module]_Block_Form extends Mage_Core_Block_Template
{
public function canShowForm()
{
$category = Mage::registry('current_category');
$product = Mage::registry('current_product');
/**
* If no current_category is set which can be because the product
* was accessed via search or direct URL retrieve all the categories from the product
*/
$categoryIds = ($category) ? array($category->getId()) : $product->getCategoryIds();
/**
* Now we'll also get the IDs for the children
*/
$filterArray = array();
foreach ($categoryIds as $id) {
$filterArray[] = array('attribute'=> 'path','like' => "%/{$id}/%");
}
$children = Mage::getModel('catalog/category')->getCollection()
->addAttributeToFilter($filterArray);
/**
* Now check if 3 belongs to parents or children
*/
if (in_array(3, $children->getAllIds()) || in_array(3, $categoryIds) ) { // 3 is the allowed category
return true;
} else {
return false;
}
}
}
You can see we have a method here that contains the business logic. It's always advised to move your business logic to a block class and not put it in the template file.
Now for adding it to the front end. In your template there should be a layout XML which you can edit. It's either a local.xml
, catalog.xml
or some template specific name. Find it and add the following.
<catalog_product_view>
<reference name="content">
<block type="[namespace]_[module]/form" name="[namespace]_[module].form" template="[namespace]_[module]/form.phtml"/>
</reference>
</catalog_product_view>
This adds the form to the main content section of the product page. If you want to display it somewhere else modify accordingly but let's use this to test it.
Now create a directory [namespace]_[module]
in the template folder and add a file form.phtml
. In that file we'll use the canShowForm
method to determine if this is a product we can show the form for.
<?php if ($this->canShowForm()):?>
<!-- The HTML of the form goes here -->
<?php endif;?>