CakePHP: escritura en tablas de 2 db desde la misma vista

I'm trying to write a small expenses cake app. Basicaly I have a expenseClaim that hasMany Expenses (expense belongsTo expenseClaim). When you add/edit a expenseClaim I want to be able to add multiple expenses for that expense claim from within that view. Could someone point me in the right direction?

Any tutorials / sample code would be massively appreciated. Thanks in advance

using cake 2.1

preguntado el 31 de julio de 12 a las 12:07

1 Respuestas

Put in expenseClaim/add:

$this->expenseClaim->Expense->create();

It should work if the relationship is well set in the model.

Si no,

$this->loadModel('Expense');
 $this->Expense->create();

siempre debería funcionar.

Edit:

$data=array
    (
        [Expense] => Array
        (
            [fieldname1] => 'value'
            [fieldname2] => 'value'
        )
    )



 $this->loadModel('Expense');
 $this->Expense->create();
            if ($this->Expense->save($data)) {
                $this->Session->setFlash(__('Done.'));

            } else {
                $this->Session->setFlash(__('Failure.'));
            }

Edit2: if you want to pass data from the view:

if ($this->request->is('post')) {
                    $this->loadModel('Expense');

        $this->Expense->create();
        if ($this->Expense->save($this->request->data)) {
            $this->Session->setFlash(__('Done.'));

        } else {
            $this->Session->setFlash(__('Failure'));
        }
    }

The request is created automatically if you use the form helper in the view.

Respondido 31 Jul 12, 12:07

Thanks for the reply, wuld you mind expanding a little on your code. So, for example, how would I tell it what data goes into the relevant expense fields? - Jaime J.

Ah ok, I follow, thank you - one last question (sorry!) would I have to hard code this in my view? For example (in view) <input name="data[Expense][sitename]" type="text" id="ExpenseSitename"> or is there another more cakey way? Thanks again - Jaime J.

Ah easier than I thought! Would this work if I wwanted to created multiple expenses (db rows) in the same save? - Jaime J.

You could either do a loop (easier) or use saveMany: book.cakephp.org/2.0/en/models/… - L. Sanna

Thank you for all your help, cake is slowly beginning to make much more sense! - Jaime J.

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.