I am displaying a customer attribute in frontend as per the configuration settings (the attribute can be displayed as dropdown, checkbox etc.)
I have used block class for the purpose so that I can use the same template file in different pages (for example: register, checkout pages etc.).
The block class structure looks like:
MagePsycho/Customer/Block/Widget/Abstract.php
MagePsycho/Customer/Block/Widget/Type/Dropdown.php
MagePsycho/Customer/Block/Widget/Type/Checkbox.php
MagePsycho/Customer/Block/Widget/Type.php
To display the attribute, you have to include the following code in .phtml:
<?php echo $this->getLayout()->createBlock('magepsycho_customer/widget_type')->setObject($this->getFormData())->toHtml() ?>
From this you can assume that Type.php
acts as a pseudo factory class for generating the required attribute type:
class MagePsycho_Customer_Block_Widget_Type extends MagePsycho_Customer_Block_Widget_Abstract
{
public function _toHtml()
{
if ($someConditionToShowDropdown) {
return $this->getLayout()->createBlock('magepsycho_customer/widget_type_dropdown')->setObject($this->getObject())->toHtml();
} else if ($someConditionToShowCheckbox) {
return $this->getLayout()->createBlock('magepsycho_customer/widget_type_checkbox')->setObject($this->getObject())->toHtml();
}
return '';
}
}
I could have added the presentation logic of _toHtml()
in .phtml but to make it look cleaner, I decided to move it to some generic block class Type.php
.
My Question here is, what is the better way to generate the block class/template based on conditions. Is the way I am doing is correct? Any Suggestions?
$someConditionToShowDropdown
is based on system settings where it says Choose Field Type: Dropdown | Checkbox