gusjap
gusjap

Reputation: 2515

Saving data to database

I'm quite new to CakePHP so my question is hopefully quite easy to answer.

I want to create a form for adding a new recipe and recipeitem at the same time. How do I do that?

I have three tables in my database: recipes, recipeitems and recipes_recipeitems;

eg.  Recipe.title
     Recipe.cookingtime
     Recipeitem.name

I tried the following but it only created a Recipepart without setting it's name or recipe_id.

Form:

<?php echo $this->Form->create('Recipe'); ?>
<fieldset>
    <legend><?php echo __('Create recipe'); ?></legend>
<?php
    echo $this->Form->input('title');
    echo $this->Form->input('cooking_time');
    echo $this->Form->input('RecipeitemName');
?>
</fieldset> 
 <?php echo $this->Form->end(__('Submit')); ?>

RecipeController:

App::import('model','RecipeItem');
class RecipesController extends AppController {
public function add() {
    if ($this->request->is('post')) {
        $this->request->data['Recipe']['user_id'] = $this->Auth->user('id');
        $this->request->data['RecipeItem']['name'] = $this->request->data['Recipe']['RecipeitemName'];
        $newRecipeItem = new RecipeItem();
        $this->Recipe->create();
        if ($this->Recipe->save($this->request->data)) {
            $this->Session->setFlash(__('The recipe has been saved'));
            //$this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The recipe could not be saved. Please, try again.'));
        }
        $this->request->data['RecipeItem']['recipe_id'] = $this->Recipe->id;
        if ($newRecipeItem->save($this->request->data)) {
            $this->Session->setFlash(__('The recipeItem has been saved'));
            $this->redirect(array('action' => 'index'));            
        } else{
            $this->Session->setFlash(__('The recipeItem could not be saved. Please, try again.'));
        }

    }
}

Upvotes: 0

Views: 92

Answers (1)

L. Sanna
L. Sanna

Reputation: 6562

$newRecipeItem = new RecipeItem();

This line is not doing what you think. It creates an instance of the RecipeItem class. But it does not make an INSERT in the database. So this line:

$newRecipeItem->save($this->request->data)

does nothing. You could use:

$this->Recipe->RecipeItem->create();

then do a save.

create() function doc

Upvotes: 2

Related Questions