mgPePe
mgPePe

Reputation: 5907

CakePHP: How to organize repeatable forms?

I have and add/edit form that adds/edits depending on whether there is an id passed.

This model is accessed by three different types of users in 3 completely different situations - different controllers, different menus, different breadcrumbs, different everything. Yet, the form is the same, the logic is the same.

So essentially I have 2 problems - repeating view form and repeating controller code.

I tried to put it in a element, but then I have to pass a variable for the action of the form to point to different controllers. And if i have the same action and use the same controller, then I have to have some kind of referer() and it's almost impossible to pass all the different data for breadcrumbs, menus, sidebars etc. i am missing something major in planning it out.

How should I organize my code with the idea to have minimum code and minimum overhead since my app is changing by the day, and i don't want to be updating 3 places and forget some of them etc.

Upvotes: 0

Views: 285

Answers (1)

deizel.
deizel.

Reputation: 11212

You can reuse controller logic by creating a component (or by placing logic in AppController):

// controllers/first_controller.php
class FirstController extends AppController {

    public $components = array('MyForm');

    public function firstAction($id = null) {
        $this->MyForm->processForm(/* params */); // inserts reusable logic
        $this->redirect(array('action' => 'index'));
    }
}

(Repeat for SecondController::secondAction() and ThirdController::thirdAction().)


You can reuse view logic by creating elements:

// views/first/first_action.ctp
$this->Html->addCrumb('First');
echo $this->Html->tag('h2', 'First');
$this->element('my_form', array(/* params */)); // inserts reusable logic

(Repeat for other views.)


I tried to put it in a element, but then I have to pass a variable for the action of the form to point to different controllers.

You can access $this->params from inside an element, saving you from having to pass in trivial things like the current action.

Upvotes: 1

Related Questions