Add a Layout Select Field to the Admin Form of Magento Custom Modules

I am coding a bespoke CMS feature for a Magento project. I wanted the client to be able to change the template / layout of each page. This is similar to the Layout selection found in the standard Magento CMS page edit screen. I added the following within the _prepareForm() function. This will display a layout selection dropdown on the Magento admin form page.

[php]
$fieldset->addField(‘root_template’, ‘select’, array(
‘label’ => Mage::helper(‘customcmsmodule’)->__(‘Root Template’),
‘name’ => ‘root_template’,
‘values’ => Mage::getSingleton(‘page/source_layout’)->toOptionArray(),
));
if (!$model->getId())
{
$model->setRootTemplate(Mage::getSingleton(‘page/source_layout’)->getDefaultValue());
}
[/php]
Mage::getSingleton(‘page/source_layout’)->toOptionArray() is a Magento function that comes handy. The conditional $model->getId() fires up when we create a new page. This will set the dropdown to the default template: 1column.phtml.

For the above to work, you will need to add the following line somewhere after the start of the function _prepareForm() {.
[php]
$model = Mage::registry(‘modulename_data’);
[/php]
I hope this helps someone! If you have any trouble or questions, please leave a comment.