Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce form code duplication in CakePHP

Tags:

cakephp

I have a form in CakePHP with a few dozen fields in it. From all the examples I have seen, there is duplicate form code for an add view and an edit view.

Is there any tricks to keep the duplication out? What is best method in CakePHP for this?

like image 829
Erik L Avatar asked Feb 04 '11 17:02

Erik L


1 Answers

What I do, is to put all form fields in an element, and then insert the element in the add.ctp and edit.ctp

Don't forget to add the hidden field with the id in the edit.ctp

This way all visible elements are in one file, easier to maintain.

View/MyModel/add.ctp
echo $this->Form->create('MyModel');
echo $this->element('my_form'); 
echo $this->Form->end();

View/MyModel/edit.ctp
echo $this->Form->create('MyModel');
echo $this->Form->input('id');
echo $this->element('my_form'); 
echo $this->Form->end();

View/Elements/my_form.ctp
// your form inputs
// whatever they are
like image 190
kaklon Avatar answered Sep 22 '22 06:09

kaklon