I have a very annoying problem with yii2. I am able to do the insertion until 12/12 of the year that I want, but when I put the day above 13 it locks as empty and inserts in the bank the value 1970-01-01. I'll put the codes in the form, the model and the controller.
Controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
if(Yii::$app->request->isAjax && $model->load($_POST))
{
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
$model->data_nascimento = date("Y-m-d", strtotime($model->data_nascimento));
$data = $model->data_nascimento;
var_dump($data);
$delet = $model->niver_deleted;
if ($delet == 0){
$delet = 'false';
}
else{
$delet = 'true';
}
$ano = substr($data, 0, 4);
$mes = substr($data, -2);
$dia = substr($data, 5, 2);
$query = Yii::$app->db2->createCommand("update funcionario set data_nascimento = '{$ano}-{$mes}-{$dia}', niver_deleted = {$delet} where id = '$id'")->queryAll();
debug_print_backtrace();
return $this->redirect(['view', 'id' => $model->id]);
}
$model->data_nascimento = Yii::$app->getFormatter()->asDate($model->data_nascimento);
var_dump($model->data_nascimento);
return $this->render('update', [
'model' => $model,
]);
}
Form
<?= $form->field($model, 'data_nascimento')->widget(DatePicker::className(), [
'language' => 'pt-BR',
'dateFormat' => 'php:d/m/Y',
'options' => ['class' => 'form-control'],
])->textInput(['maxlength' => 10, 'placeholder' => "__/__/____"]) ?>
<?= $form->field($model, 'niver_deleted')->dropDownList(['1' => 'Sim', '0' => 'Não'],['prompt'=>'Selecione uma opção']) ?>
</div>
<div class="box-footer">
<?= Html::submitButton(Yii::t('app', 'Salvar'), ['class' => 'btn btn-success btn-flat']) ?>
<?= Html::a(Yii::t('app', 'Voltar'), ['index'], ['class' => 'btn btn-danger btn-flat']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script>
jQuery(function($) {
$("#aniversario-data_nascimento").mask("99/99/9999");
});
</script>
Model
public function validateData($attribute, $params)
{
$date = date('d/m/Y');
if (strtotime($date) < strtotime($this->$attribute))
$this->addError($attribute, 'Data não pode ser superior à hoje.');
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['codigo', 'nome'], 'required'],
[['data_nascimento'], 'safe'],
[['niver_deleted'], 'boolean'],
['data_nascimento', 'date', 'format' => 'php:d/m/Y', 'message' => 'Data inválida.'],
[['nome'], 'string', 'max' => 80],
['data_nascimento', 'validateData'],
];
}