Tengo un formulario donde a través del CJui.DatePicker ingreso la fecha de nacimiento, ¿como haría para calcular la edad a través de esa fecha y guardarlo en la base de datos directamente sin mostrarlo?, es decir ¿como paso el parámetro $_POST[‘nacimiento’] al controlador para guardarlo en el actionCreate? y disculpen las molestias de antemano.
PD: No es necesario Ajax con que lo haga luego de hacer el submit me basta.
Este es el form
<?php
/* @var $this SolicitantesController */
/* @var $model Solicitantes */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'solicitantes-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>true,
'stateful'=>true,
'clientOptions' => array(
),
)); ?>
<p class="note">Campos con <span class="required">*</span> son Obligatorios.</p>
<div class="row">
<?php echo $form->labelEx($model,'cedula'); ?>
<?php echo $form->textField($model,'cedula',array('size'=>12,'maxlength'=>12, 'id'=>'cedula')); ?>
<?php echo $form->error($model,'cedula', array('id'=>'cederror')); ?>
</div>
<script>
$('#cedula').on('blur', function(){
$.ajax({
url: <?php echo "'".CController::createUrl('solicitantes/ExistePersona')."'"; ?>,
data: {'cedula' : $('#cedula').val()},
type: "post",
success: function(data){
// AQUÍ POR EJEMPLO RECUPERAS UN ARRAY CON LOS DATOS DE
// LA PERSONA O NULL SI NO HAY DATOS. ENTONCES COMPRUEBAS
// SI "data" ES NULL. SI NO LO ES, RELLENAS TUS CONTROLES
// CON LOS DATOS DEL ARRAY Y LISTO.
if (data == 0)
{
nombre.value = " ";
nombre.disabled = false;
apellido.value = " ";
apellido.disabled = false;
nacimiento.value = " ";
nacimiento.disabled = false;
edad.value = " ";
edad.disabled = false;
sexo.value = " ";
sexo.disabled = false;
direccion.value = " ";
direccion.disabled = false;
numerocasa.value = " ";
numerocasa.disabled = false;
telefono.value = " ";
telefono.disabled = false;
email.value = " ";
email.disabled = false;
circuitos_id.value=" ";
circuitos_id.disabled = false;
}
else
{
var retrievedJSON = data;
var array = JSON.parse(retrievedJSON);
nombre.value = array[0].nombre;
nombre.disabled = true;
apellido.value = array[0].apellido;
apellido.disabled = true;
nacimiento.value = array[0].nacimiento;
nacimiento.disabled = true;
edad.value = array[0].edad;
edad.disabled = true;
sexo.value = array[0].sexo;
sexo.disabled = true;
direccion.value = array[0].direccion;
direccion.disabled = true;
numerocasa.value = array[0].numerocasa;
numerocasa.disabled = true;
telefono.value = array[0].telefono;
telefono.disabled = true;
email.value = array[0].email;
email.disabled = true;
circuitos_id.value=array[0].circuitos_id;
circuitos_id.disabled = true;
}
}
});
})
</script>
<div class="row">
<?php echo $form->labelEx($model,'nombre'); ?>
<?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>100, 'id'=>'nombre')); ?>
<?php echo $form->error($model,'nombre'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'apellido'); ?>
<?php echo $form->textField($model,'apellido',array('size'=>60,'maxlength'=>100, 'id'=>'apellido')); ?>
<?php echo $form->error($model,'apellido'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nacimiento'); ?>
<?php
$fecha = date('Y') - 15;
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'attribute' => 'nacimiento',
'language' => 'es',
'id'=> 'nacimiento',
'options' => array(
'dateFormat' => 'yy-mm-dd', // format of "2012-12-25"
'showOtherMonths' => true, // show dates in other months
'selectOtherMonths' => true, // can seelect dates in other months
'changeYear' => true, // can change year
'changeMonth' => true, // can change month // maximum date
'yearRange'=>'1910:2000',
'defaultDate'=> '1910-01-01',
),
'htmlOptions' => array(
'size' => '15', // textField size
'maxlength' => '10', // textField maxlength
),)); ?>
<?php echo $form->error($model,'nacimiento'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'sexo'); ?>
<?php echo $form->dropDownList($model,'sexo', array(''=>'Seleccione el sexo', '1' => 'Masculino', '2' => 'Femenino'), array('id'=>'sexo')); ?>
<?php echo $form->error($model,'sexo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'direccion'); ?>
<?php echo $form->textField($model,'direccion',array('size'=>60,'maxlength'=>255, 'id'=>'direccion')); ?>
<?php echo $form->error($model,'direccion'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'numero casa'); ?>
<?php echo $form->textField($model,'numerocasa',array('size'=>15,'maxlength'=>15, 'id'=>'numerocasa')); ?>
<?php echo $form->error($model,'numerocasa'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'telefono'); ?>
<?php echo $form->textField($model,'telefono',array('size'=>15,'maxlength'=>12, 'id'=>'telefono')); ?>
<?php echo $form->error($model,'telefono'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>255, 'id'=>'email')); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'circuitos_id'); ?>
<?php echo $form->dropDownList($model,'circuitos_id', CHtml::listData(Circuitos::model()->findAll(), 'id', 'nombre'),array('empty'=>'Seleccione un circuito', 'id'=>'circuitos_id')); ?>
<?php echo $form->error($model,'circuitos_id'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Crear' : 'Guardar'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
y este el controlador
<?php
class SolicitantesController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view', 'existepersona', 'obtenerhora'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update', 'existepersona', 'obtenerhora'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete', 'existepersona', 'obtenerhora'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Solicitantes;
$this->performAjaxValidation($model);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Solicitantes']))
{
$model->attributes=$_POST['Solicitantes'];
$model->usuarios_id = Yii::app()->user->id;
if($model->save())
$this->redirect(array('view','id'=>$model->cedula));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$this->performAjaxValidation($model);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Solicitantes']))
{
$model->attributes=$_POST['Solicitantes'];
if($model->save())
$this->redirect(array('view','id'=>$model->cedula));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Solicitantes');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Solicitantes('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Solicitantes']))
$model->attributes=$_GET['Solicitantes'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer $id the ID of the model to be loaded
* @return Solicitantes the loaded model
* @throws CHttpException
*/
public function loadModel($id)
{
$model=Solicitantes::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'La pagina solicitada no existe.');
return $model;
}
/**
* Performs the AJAX validation.
* @param Solicitantes $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='solicitantes-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function actionExistePersona ()
{
if($_POST['cedula']){
$cedula = $_POST['cedula'];
$datos = Yii::app()->db->createCommand("SELECT nombre, apellido, nacimiento, edad, sexo, direccion, numerocasa, telefono, email, circuitos_id FROM solicitantes WHERE cedula = ".$cedula)->queryAll();
echo(($datos)?json_encode($datos):'');}
else{
$datos = 0;
echo(($datos)?json_encode($datos):''); }
}
}