November 22, 2007
If I have a few views, add.ctp, edit.ctp all using the same code for the form.
I have created another view file called _form.ctp
For displaing same part we call $this->renderPartial(’_form’);
How I implement it?
All we need is overload View class with renderPartial function implementation. The goal of function is call renderElement with correct path to view.
<?php
class ExtView extends View
{
function renderPartial($name, $params = array(), $loadHelpers = false) {
if ((strpos($name, ‘\\’)===false) && (strpos($name, ‘/’)===false)) {
$name = ‘..’ . DS . Inflector::underscore($this->name) . DS . $name;
}
return $this->renderElement($name, $params, $loadHelpers);
}
}
?>
Now in app_controller all I need is set default view class in beforeRender callback:
<?php
class AppController extends Controller {
function beforeRender() {
$this->view=‘Ext’;
return true;
}
}
?>
November 25, 2007 at 8:37 pm
They are not completely the same. In the edit.ctp there is input(’id’)?> and as I know it doesn’t exist in add.ctp.
I check $this->action and show it if action!=’add’.
But you’re right - my add.ctp & edit.ctp are often completely the same.
November 27, 2007 at 10:57 am
See next post for real example.
Using renderPartial does not limited only add/edit case, but for this example RoR render partial for common code. So I choose this for example.
November 27, 2007 at 12:01 pm
Aha, got it. Nice.