2 Modelos Para 1 Solo Formulario

Tengo un formulario para 2 modelos, solicitantes y solicitudes, donde en el primer campo de la cédula si la escribo ya esta registrada me carga todos los campos de solicitantes en el formulario, mi duda es la siguiente como hago para que cuando el solicitante exista osea que me cargue los datos en el form a través de mi función ajax me registre en la base de datos solo los nuevos datos de la solicitud con el id del solicitante que me mostró el form. Espero puedan ayudarme muchas gracias

El código del formulario es:




<?php

/* @var $this SolicitudesSocialController */

/* @var $model SolicitudesSocial */

/* @var $form CActiveForm */

?>


<div class="form">


<?php 




$form=$this->beginWidget('CActiveForm', array(

	'id'=>'solicitudes-social-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'=>false,

)); 

if ($a->isNewRecord==false) {$b=Solicitantes::model()->findByPk($a->solicitantes_id); }

echo $form->errorSummary(array($a,$<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='B)' />); 

?>


	<p class="note">Campos con <span class="required">*</span> son Obligatorios.</p>

	<?php if (Yii::app()->controller->action->id=="create"){?>    

	<div class="row">

		<?php echo $form->labelEx($b,'cedula'); ?>

		<?php echo $form->textField($b,'cedula',array('size'=>12,'maxlength'=>12, 'id'=>'cedula')); ?>

		<?php echo $form->error($b,'cedula', array('id'=>'cederror')); ?>

	</div>

    <?php } ?>

    

    <?php if (Yii::app()->controller->action->id == "update"){?> 

    <div class="row">

		<?php echo $form->labelEx($b,'cedula'); ?>

		<?php echo $form->label($b, $b->cedula); ?>

		<?php echo $form->error($b,'cedula', array('id'=>'cederror'));  ?>

	</div>

    <?php } ?>

    

    <script>

    $('#cedula').on('blur', function(){

		$.ajax({

     		url: <?php echo "'".CController::createUrl('solicitudesSocial/ExistePersona')."'"; ?>,

     		data: {'cedula' : $('#cedula').val()},

     		type: "post",

     		success: function(data){

				if (data == 0)

				{

					nombre.value = " ";

					nombre.disabled = false;

					apellido.value = " ";

					apellido.disabled = false;

					nacimiento.value = " ";

					nacimiento.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;

					$("#button").css("display", "block");

				}

				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;

					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;

					$("#button").css("display", "none");

				}

			}

		});

	})

</script>

    

	<div class="row">

		<?php echo $form->labelEx($b,'nombre'); ?>

		<?php echo $form->textField($b,'nombre',array('size'=>60,'maxlength'=>100, 'id'=>'nombre')); ?>

		<?php echo $form->error($b,'nombre'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($b,'apellido'); ?>

		<?php echo $form->textField($b,'apellido',array('size'=>60,'maxlength'=>100, 'id'=>'apellido')); ?>

		<?php echo $form->error($b,'apellido'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($b,'nacimiento'); ?>

        <?php

		$fecha = date('Y') - 15;

		$this->widget('zii.widgets.jui.CJuiDatePicker', array(

    		'model' => $b,

    		'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',

				'value'=>$b->nacimiento,

    		),

    		'htmlOptions' => array(

        	'size' => '15',         // textField size

        	'maxlength' => '10',    // textField maxlength

    	),)); ?>

		<?php echo $form->error($b,'nacimiento'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($b,'sexo'); ?>

		<?php echo $form->dropDownList($b,'sexo', array(''=>'Seleccione el sexo', '1' => 'Masculino', '2' => 'Femenino'), array('id'=>'sexo')); ?>

		<?php echo $form->error($b,'sexo'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($b,'direccion'); ?>

		<?php echo $form->textField($b,'direccion',array('size'=>60,'maxlength'=>255, 'id'=>'direccion')); ?>

		<?php echo $form->error($b,'direccion'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($b,'numero casa'); ?>

		<?php echo $form->textField($b,'numerocasa',array('size'=>15,'maxlength'=>15, 'id'=>'numerocasa')); ?>

		<?php echo $form->error($b,'numerocasa'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($b,'telefono'); ?>

		<?php echo $form->textField($b,'telefono',array('size'=>15,'maxlength'=>12, 'id'=>'telefono')); ?>

		<?php echo $form->error($b,'telefono'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($b,'email'); ?>

		<?php echo $form->textField($b,'email',array('size'=>60,'maxlength'=>255, 'id'=>'email')); ?>

		<?php echo $form->error($b,'email'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($b,'circuitos_id'); ?>

		<?php echo $form->dropDownList($b,'circuitos_id', CHtml::listData(Circuitos::model()->findAll(), 'id', 'nombre'),array('empty'=>'Seleccione un circuito', 'id'=>'circuitos_id')); ?>

		<?php echo $form->error($b,'circuitos_id'); ?>

	</div>

    

    <div class="row">

		<?php echo $form->labelEx($a,'tipo_solicitudes_id'); ?>

		<?php echo $form->textField($a,'tipo_solicitudes_id',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->error($a,'tipo_solicitudes_id'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($a,'departamentos_id'); ?>

		<?php echo $form->textField($a,'departamentos_id',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->error($a,'departamentos_id'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($a,'solicitantes_id'); ?>

		<?php echo $form->textField($a,'solicitantes_id',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->error($a,'solicitantes_id'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($a,'fecha'); ?>

		<?php echo $form->textField($a,'fecha'); ?>

		<?php echo $form->error($a,'fecha'); ?>

	</div>

    

    <div class="row">

		<?php echo $form->labelEx($b,'usuarios'); ?>

		<?php echo $form->textField($b,'usuarios_id'); ?>

		<?php echo $form->error($b,'usuarios_id'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($a,'descripcion'); ?>

		<?php echo $form->textArea($a,'descripcion',array('rows'=>6, 'cols'=>50)); ?>

		<?php echo $form->error($a,'descripcion'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($a->isNewRecord ? 'Crear' : 'Guardar'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->



El codigo del controlador es:




<?php


class SolicitudesSocialController 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', 'calcularEdad'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('@'),

			),

			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 SolicitudesSocial;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['SolicitudesSocial']))

		{

			$model->attributes=$_POST['SolicitudesSocial'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}*/

	

	public function actionCreate()

	{

		$a=new SolicitudesSocial;

		$b=new Solicitantes;

		$this->performAjaxValidation(array($a,$<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='B)' />);

		if(isset($_POST['SolicitudesSocial'],$_POST['Solicitantes']))

		{

			$a->attributes=$_POST['SolicitudesSocial'];

			$b->attributes=$_POST['Solicitantes'];

			

			$valid=$a->validate();

			$valid=$b->validate() && $valid;

			$fechaNacimiento = $b->nacimiento;

            //Aqui puedes mandar a llamar un metodo que te calcule la edad p.e.

            $edad = $this->calcularEdad($fechaNacimiento);

            //Antes de guardar

            $b->edad = $edad;

			

			if($valid)

			{

				$a->save(false);

				$b->save(false);

			}

			$this->redirect(array('view','id'=>$a->id));

		}

	$this->render('create',array(

	'a'=>$a,

	'b'=>$b

	));

	}




	/**

	 * 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);


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['SolicitudesSocial']))

		{

			$model->attributes=$_POST['SolicitudesSocial'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}*/

	public function actionUpdate($id)

	{

		$a=new SolicitudesSocial;

		$b=new Solicitantes;

		$this->performAjaxValidation(array($a,$<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='B)' />);

		$a=$this->loadModel($id);

		if(isset($_POST['SolicitudesSocial'],$_POST['Solicitantes']))

		{

			$a->attributes=$_POST['SolicitudesSocial'];

			$b->attributes=$_POST['Solicitantes'];

			$b->solicitantes_id=$a->id;

			$b->setIsNewRecord(false);

			if($a->save() && $b->update())

			$this->redirect(array('view','id'=>$a->id));

		}

		$this->render('update',array('a'=>$a,'b'=>$<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='B)' />);

	}


	/**

	 * 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('SolicitudesSocial');

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new SolicitudesSocial('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['SolicitudesSocial']))

			$model->attributes=$_GET['SolicitudesSocial'];


		$this->render('admin',array(

			'model'=>$model,

		));

	}

	

	public function actionListarSolicitantes($term)

	{

		$criteria = new CDbCriteria;

		$criteria->condition = "LOWER(nombre) like LOWER(:term) or LOWER(apellido) like LOWER(:term)

		or (nacimiento) like LOWER(:term)";

		$criteria->params = array(':term'=> '%'.$_GET['term'].'%');

		$criteria->limit = 30;

		$models = Solicitantes::model()->findAll($criteria);

		$arr = array();

		foreach($models as $model)

		{

			$arr[] = array(

			'label'=>($model->nombre.' '.$model->apellido.' ('.$model->nacimiento.')'), // label for dropdown list

			'value'=>($model->nombre.' '.$model->apellido.' ('.$model->nacimiento.')'), // value for input field

			'id'=>$model->id, // return value from autocomplete

			);

		}

		echo CJSON::encode($arr);

	}


	/**

	 * 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 SolicitudesSocial the loaded model

	 * @throws CHttpException

	 */

	public function loadModel($id)

	{

		$model=SolicitudesSocial::model()->findByPk($id);

		if($model===null)

			throw new CHttpException(404,'La pagina solicitada no existe.');

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param SolicitudesSocial $model the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='solicitudes-social-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):'');

		}

	}

	

	public function calcularEdad($fechaNacimiento) 

	{

    	list($Y,$m,$d) = explode("-",$fechaNacimiento);

    	return( date("md") < $m.$d ? date("Y")-$Y-1 : date("Y")-$Y );

	}

}