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
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->_flash(__('The Post has been saved.', true),'success');
                                $this->redirect(array('action'=>'view',$this->Video->id));
                        }
                        else {
                                $this->_flash(__('The Post could not be saved. Please, try again.', true),'warning');
                        }
                }
                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');?>

Reply

  • Allowed HTML tags: <b> <br> <p> <a> <strong> <cite> <em> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You may use [img:xx] tags to display uploaded files or images inline.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <css>, <diff>, <drupal5>, <html>, <javascript>, <php>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options