当我在SalasController debug($this->data)
方法上reservar()
时,来自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();
});
}
答案 0 :(得分:0)
我之前在@Holt提示之后保存;
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);
}
}
}