簡體   English   中英

Cakephp的beforeSave()不使用$ model :: save()保留新數據

[英]Cakephp's beforeSave() not retaining new data using $model::save()

當我在SalasController reservar()方法上執行debug($this->data)時,來自json的$ data可以,但是當我執行this->Sala->save($this->data)並嘗試debug($data)beforeSave()返回:

Notice (8): Undefined property: FormataDataBehavior::$data [APP\Model\Behavior\FormataDataBehavior.php, line 52]
\app\Model\Behavior\FormataDataBehavior.php (line 52)
null

SalasController.php

App::uses('AppController', 'Controller');

class SalasController extends AppController {

public $components = array('RequestHandler');

public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('listar', 'reservar');
    $this->RequestHandler->addInputType('json', array('json_decode', true));
}
    public function reservar() {
    $this->Sala->save($this->data); //no conditions just for debugging.
}

模型Sala.php

class Sala extends AppModel {

public $useTable = 'agenda';
public $actsAs = array(
    'FormataData' => array('dia')
);

行為

class FormataDataBehavior extends ModelBehavior {

// Armazena os campos do model a serem formatados.
public $campos;

//Inicializa o behavior
public function setup(Model $model, $settings = array()) {
    if (!empty($settings)) {
        $this->campos[$model->name] = $settings;
    } else {
        throw new MethodNotAllowedException('Campos data não informados na declaração do behavior');
    }
}

public function beforeSave(Model $model, $options = array()) {
    parent::beforeSave($model, $options);
    debug($this->data); //trying show data, but is !isset... =/
    die();
}

MyJs

function adicionarReserva() {
var dadosForm = {Sala: {}};
$.each($("#form-reservas").serializeArray(), function(index, value) {
    dadosForm.Sala[value.name] = value.value;
});
$.post("/intracake/Salas/reservar.json", dadosForm)
        .done(function(data) {
            sysMsg(data.html);
            atualizaTabelas();
        });
}

我的@Holt提示后的beforeSave;

public function beforeSave(Model $model, $options = array()) {
    parent::beforeSave($model, $options);
    $this->formataBeforeSave($model);
    return true;
}

public function formataBeforeSave(Model &$model, $padrao = 'Y-m-d') {
    foreach ($this->campos[$model->name] as $campo) {
        if (isset($model->data[$model->name][$campo]) && !empty($model->data[$model->name][$campo])) {
            $model->data[$model->name][$campo] = $this->converte($model, $model->data[$model->name][$campo], $padrao);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM