Merge your Add and Edit actions into a Single Form in CakePHP

Posted by Mr PHP on

This CakePHP example will show you how to merge your Add and Edit forms into a Single Form action.

This may be of benefit if you have a form with complex controller logic that you don’t want to duplicate.

The Controller

We redirect the add and edit actions to use the form action.


class PostsController extends AppController {
	var $name = 'Posts';

	function add() {
	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->_flash(__('Invalid Post.', true),'error');
	function form($id = null) {
		if (!empty($this->data)) {
			if ($this->Post->save($this->data)) {
				$this->Session->setFlash(__('The Post has been saved.', true));
			else {
				$this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));
		if (empty($this->data)) {
			$this->data = $this->Post->read(null, $id);

The View

The view can be copied from your current edit template.


<?php echo $form->create('Post');?>
 		<legend><?php __('Post Details');?></legend>
		echo $form->input('id');
		echo $form->input('name');
		echo $form->input('body');
		echo $form->input('active',array('type'=>'checkbox'));
<?php echo $form->end('Submit');?>

Tagged with : CakePHP