2
votes

Since CakePHP is updated to 2.3.5, I have problem to save data. I don't want to save datas who contains no price.

My method beforeSave in my model looks like this :

public function beforeSave($options = array()){
    if(empty($this->data['MyModel']['price'])){
        unset($this->data['MyModel']);
    } 
    return true;
}

Since my update, i've found this in /lib/Model/Model.php (l. 1751)

if ($success && $count === 0) {
    $success = false;
}

If i comment this 3 lines my problem is solved. Do you know a method in my beforeSave who don't block my saving ?

If i use data validation, all my datas are not saved with my saveAll.

Exemple model "Option" validator:

public $validate = array(
    'prix' => array(
        'rule'       => 'notEmpty'
    )
);

Exemple datas to save :

array(
'Commande' => array(
    'nature_commande' => '0',
    'base_id' => '1',
    'nom' => 'Test',
    'chef_id' => '531',
),
'Option' => array(
    (int) 0 => array(
        'prix' => '5456'
    ),
    (int) 1 => array(
        'prix' => '45645'
    ),
    (int) 3 => array(
        'prix' => ''
    )
)

saveAll in my Controller "Commande" (return false):

debug($this->Commande->saveAll($this->request->data, array('validate' => 'first')));

I would like my datas be saved out of the last row in my Model "Options" => 3. I can use foreach in my controler to delete the blank row but can i make it better ?

1
CakePHP 2.3.5? Latest release is 2.3.0 :-?Álvaro González
$count is the number of fields. If you are unsetting everything in $this->data[], then you will have no fields for cake to save, hence that condition is met. Your logic/code is wrong, cake's model code is fine. Use cakes built-in validationRoss

1 Answers

1
votes

Have you thought about using CakePHP's built-in data validation? This would allow you to specify that you don't want to save unless the 'price' is a certain amount, greater than zero, between a range...etc etc etc.

Basically, you set up rules for your fields, and any time you try to save a row, it makes sure each field passes whatever validation you set up.

It has a ton of validation types including valid email, number ranges, phone numbers, regex and more.