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

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.

controllers/posts_controller.php
<?php
class PostsController extends AppController {
	var $name = 'Posts';

	function add() {
		$this->admin_form();
		$this->render('form');
	}
	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->_flash(__('Invalid Post.', true),'error');
			$this->redirect(array('action'=>'index'));
		}
		$this->admin_form($id);
		$this->render('form');
	}
	
	function form($id = null) {
		if (!empty($this->data)) {
			$this->Post->create();
			if ($this->Post->save($this->data)) {
				$this->Session->setFlash(__('The Post has been saved.', true));
				$this->redirect(array('action'=>'view',$this->Video->id));
			}
			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.

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

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <i> <strong> <cite> <em> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <css>, <diff>, <drupal5>, <html>, <javascript>, <php>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.