6

I'm using CakePHP 2.6.7.

A user will be able to add to his profile multiple cars and multiple addresses. He will also be able to link multiple addresses to one car, and link one address to multiple cars.

I then have a User model with :

class User extends AppModel {
    public $hasMany = array(
        'Car',
        'Address'
    );
}

A Car model with :

class Car extends AppModel {
    public $belongsTo = array(
        'User'
    );

    public $hasAndBelongsToMany = array(
        'Address' =>
            array(
                'unique' => 'keepExisting'
            )
    );
}

An an Address model :

class Address extends AppModel {
    public $hasAndBelongsToMany = array(
        'Car' =>
            array(
                'unique' => 'keepExisting',
            ),
    );

    public $belongsTo = array(
        'User'
    );
}

I have a form so that the user can edit his cars (only one for the moment) :

[...]

        <legend>Mes voitures</legend>

        <?php
            for($nbrvoiture = 0; $nbrvoiture <= 0; $nbrvoiture++)
            {
                ?><h3>Voiture <?php echo $nbrvoiture+1?></h3><?php
                $myLabelOptions = array('text' => "Marque");
                echo $this->Form->input('Car.'.$nbrvoiture.'.CarMake', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));

                $myLabelOptions = array('text' => "Modèle");
                echo $this->Form->input('Car.'.$nbrvoiture.'.CarModel', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));

                $myLabelOptions = array('text' => "Plaque d'immatriculation");
                echo $this->Form->input('Car.'.$nbrvoiture.'.NumberPlate', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));


                echo $this->Form->submit("Valider", array(
                    'class' => 'btn btn-default col-sm-offset-2'
                ));
            }

The thing is that I can't save the data to my database. Here is part of the User controller code :

function edit() {
    // On récupère l'ID de l'utilisateur
    $user_id = $this->Auth->user('id');

    // Si l'utilisateur n'a pas d'ID => il n'est pas connecté => il ne peut pas éditer son profil
    if(!$user_id){
        $this->redirect('/');
        die();
    }

    debug($this->User->find('all'));

    $this->User->id = $user_id;
    $passError = false;

    if($this->request->is('put') || $this->request->is('post')){
        $d = $this->request->data;

        $d['User']['id'] = $user_id;
        debug($d);


        if($this->request['pass'][0]=='cars')
        {

            if($this->User->saveAssociated($d, array('deep' => true))){
                $this->Session->setFlash(__("Les informations sur la voiture ont bien été modifiées"), 'alert', array (
                    'plugin' => 'BoostCake',
                    'class' => 'alert-success'
                ));
            }else{
                $this->Session->setFlash(__("Impossible de modifier ou d'ajouter les infos"), 'alert', array (
                    'plugin' => 'BoostCake',
                    'class' => 'alert-danger'
                ));
            }
        }

When I save the data, it shows the error.

In my database I have these 4 tables :

Users(id, username, mail, password, created, lastlogin, active, firstname, lastname, gender, birthdate, phonenumber)
Cars(id, CarMake, CarModel, NumberPlate, user_id)
Addresses(id, address, city, state, postcode, country, user_id)
Addresses_cars(address_id, car_id)

This is an example of what I can get from the form (the $d variable) :

array(
    'Car' => array(
        (int) 0 => array(
            'CarMake' => 'Allard',
            'CarModel' => '2005',
            'NumberPlate' => '56QDS1'
        )
    ),
    'User' => array(
        'id' => '1'
    )
)

I don't understand why it doesn't work... Can you help me please ?

Thank you ! :)

EDIT : I also tried with SaveAll but I can't get it to work.. what's wrong?

  • 1
    "it shows the error", but then you don't list the error. What error are you getting? – Dave Jun 30 '15 at 04:50
  • It showed the error that I chose to show in case of failure ($this->Session->setFlash(__("Impossible de modifier ou d'ajouter les infos")). Anyway the problem is solved. It was validation rules for another form that were conflicting with this one. – William Gérald Blondel Jun 30 '15 at 17:13
  • That's not an error - that's a message. For future questions, please make sure to be accurate in your description and include the actual error/message so as not to waste people's time who want to help you. – Dave Jun 30 '15 at 21:59
  • Sorry for this waste of time. I thought it would be clear since it's in the code :) – William Gérald Blondel Jul 01 '15 at 13:52
  • Just trying to make sure you understand the difference between an "error" and a message you choose to show based on an expected code logic. – Dave Jul 01 '15 at 14:05
  • Yes I understand :-) . That was also a problem : it didn't give any error but it showed the message saying it failed, and I wanted to know why it failed. I solved the problem by debugging the variable that stocks the validation errors and I saw that it was trying to validate fields that were in another form (wtf?). I reorganised the code and it's all good now. – William Gérald Blondel Jul 01 '15 at 14:10

1 Answers1

1

It's already been solved by OP, but for future CakePHPers, if you have a save() or saveAll() that isn't saving (checked by your if:else block), the most common problem is a validation error.

CakePHP 2.x Data Validation

CakePHP 3.x Data Validation

If that's not it, try looking at any behaviors you're using, and check for anywhere that should be returning true and isn't (like in it's `beforeSave() method).

Dave
  • 28,833
  • 23
  • 113
  • 183