Dos Modelos En Un Form

Buenas tardes amigos, tengo un problema al trabajar con dos modelos en un form les cuento un poco, ya tengo funcionando la parte visual, el problema surge cuando voy a guardar el registro en la tabla, tengo dos dropDownList uno para el $model y otro para $b cuando realizo en el controler un implode de $b con la lista me da error: implode(): Invalid arguments passed , implode(",", null). Entonces pense que era un problema de la insercion del model $b pero no lo es debido que agregue otro campo del modelo $b lo verifique y efectivamente estaba llegando al actionCreate con el valor perfecto. Espero haberme explicado, les dejo el form y el actioncreate.

Espero puedan ayudarme o darme una idea de que pasa, Gracias.

_form.php




<?php

/* @var $this PreguntaController */

/* @var $model Pregunta */

/* @var $form CActiveForm */

?>


<div class="form">


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

	'id'=>'pregunta-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,

		

)); 


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


?>


	<p class="note">Los campos con <span class="required">*</span> son obligatorios.</p>


	<?php //echo $form->errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'descripcion_pregunta'); ?>

		<?php echo $form->textField($model,'descripcion_pregunta',array('size'=>60,'maxlength'=>600)); ?>

		<?php echo $form->error($model,'descripcion_pregunta'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'id_caracteristica'); ?>

			<?php echo $form->dropDownList($model, 'id_caracteristica', CHtml::listData(

                    Caracteristica::model()->findAll(), 'id_caracteristica', 'nombre_caracteristica'), array('multiple'=>true )); ?>

	</div>




<div class="row">

	<?php echo $form->labelEx($model,'id_aspecto'); ?>

			<?php echo $form->dropDownList($model, 'id_aspecto', CHtml::listData(

                    Aspecto::model()->findAll(), 'id_aspecto', 'nombre_aspecto')); ?>

	</div>




	<div class="row">

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

			<?php echo $form->dropDownList($b, 'id_metrica', CHtml::listData(

                    Metrica::model()->findAll(), 'id_metrica', 'nombre_metrica'), array('multiple'=>true )); ?>

		</div>


<div class="row">

	<?php echo $form->labelEx($model,'estatus_pregunta'); ?>

		<? $options = array ('1' => 'Activa', '0' => 'Inactivo'); 

		echo CHtml::dropDownList('estatus_pregunta', '1', $options);?>

	</div>




	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

		

	</div>


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


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






PreguntaController.php




	public function actionCreate()

	{

		$model=new Pregunta;

		$b = new Metrica;

		// Uncomment the following line if AJAX validation is needed

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


		if(isset($_POST['Pregunta'] , $_POST['Metrica']))

		{

				

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

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

			

							

			$model->descripcion_pregunta = $model->descripcion_pregunta;

			$arr2 = implode(",",$model->attributes['id_caracteristica']);

			$model->id_caracteristica=$arr2;

			

			$model->id_aspecto = $model->id_aspecto;

			$model->estatus_pregunta = $model->estatus_pregunta;

			$model->save();

		

			$arr = implode("," , $b->attributes['id_metrica']);

			$b->id_metrica=$arr;	

			foreach($arr as $met){

					$b->id_metrica =$met;

					$b->id_pregunta = $model->id_pregunta;

					$b->save();

				}

					

		}

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

			'model'=>$model,

			'b'=>$b,

		));

		

	}




Hola,

¿Podrías poner tu modelo Metrica?

Saludos.

Aqui esta amigo

models Metrica.php


<?php


/**

 * This is the model class for table "metrica".

 *

 * The followings are the available columns in table 'metrica':

 * @property integer $id_metrica

 * @property string $nombre_metrica

 * @property integer $valor

 */

class Metrica extends CActiveRecord

{

	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'metrica';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('valor', 'numerical', 'integerOnly'=>true),

			array('nombre_metrica', 'length', 'max'=>150),

			// The following rule is used by search().

			// @todo Please remove those attributes that should not be searched.

			array('id_metrica, nombre_metrica, valor', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id_metrica' => 'Id Metrica',

			'nombre_metrica' => 'Nombre Metrica',

			'valor' => 'Valor',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 *

	 * Typical usecase:

	 * - Initialize the model fields with values from filter form.

	 * - Execute this method to get CActiveDataProvider instance which will filter

	 * models according to data in model fields.

	 * - Pass data provider to CGridView, CListView or any similar widget.

	 *

	 * @return CActiveDataProvider the data provider that can return the models

	 * based on the search/filter conditions.

	 */

	public function search()

	{

		// @todo Please modify the following code to remove attributes that should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('id_metrica',$this->id_metrica);

		$criteria->compare('nombre_metrica',$this->nombre_metrica,true);

		$criteria->compare('valor',$this->valor);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}


	/**

	 * Returns the static model of the specified AR class.

	 * Please note that you should have this exact method in all your CActiveRecord descendants!

	 * @param string $className active record class name.

	 * @return Metrica the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}

}



Prueba con esto:

En la función rules, donde sale esto


array('valor', 'numerical', 'integerOnly'=>true),



pon esto


array('valor, id_metrica', 'numerical', 'integerOnly'=>true),

Me cuentas como te va.

Saludos.

Muchas gracias amigo me funciono perfecto, pero ahora cuando le doy a crear no me hace nada se queda en la misma ventana, no me muestra error ni nada .

Claro, porque al parecer guarda pero luego no hace nada más.

Ponle un redirect, cuando terminas de guardar, despues del último save():




if(isset($_POST['Pregunta'] , $_POST['Metrica']))

{

   ...

   ...


   $this->redirect(array('action'));

}  



Claro amigo lo habia borrado, Gracias.<br />

<br />

Ahora tengo otro problema y es cuando quiero actualizar el resgistro y es debido que yo creo una pregunta tengo una lista desplegable multiselect y cuando lo guardo en la BD por cada opcion que seleccione de la lista guardo un registro diferente, pero como hago para cuando quiera actualizar me muestre en el form los datos guardados?<br />

<br />

<br />

Asi llevo mi Update <br />


<br />

public function actionUpdate($id)<br />

	{<br />

		$model=new Pregunta; //Aqui guardo solo la pregunta <br />

		$b = new Metrica;    //aqui tengo el poll de todas las posibles respuestas<br />

	        $c= new OpcionRespuesta; //aqui guardo las metricas asociadas a una pregunta<br />

		//$model=$this-&gt;loadModel($id);<br />

		//$b=$this-&gt;loadModel($id);<br />

		// Uncomment the following line if AJAX validation is needed<br />

		 $this-&gt;performAjaxValidation($model,$b,$c);<br />

		$model=$this-&gt;loadModel($id);<br />

		$c = OpcionRespuesta::model()-&gt;findByAttributes(array('id_pregunta'=&gt;$model-&gt;id_pregunta));<br />

		//$b=$this-&gt;loadModel($id);<br />

		if(isset($_POST['Pregunta'],$_POST['Metrica'],$_POST['OpcionRespuesta']))<br />

		{<br />

			$model-&gt;attributes=$_POST['Pregunta'];<br />

			$b-&gt;attributes=$_POST['Metrica'];<br />

			$c-&gt;attributes=$_POST['OpcionRespuesta'];<br />

<br />

			$c-&gt;id_pregunta=$model-&gt;id_pregunta;<br />

			$b-&gt;setIsNewRecord(false);<br />

			<br />

			if($model-&gt;save() &amp;&amp; $b-&gt;update() &amp;&amp; $c-&gt;update)<br />

				$this-&gt;redirect(array('view','id'=&gt;$model-&gt;id_pregunta));<br />

		}<br />

<br />

		$this-&gt;render('update',array(<br />

			'model'=&gt;$model,<br />

			'b'=&gt;$b,<br />

			'c'=&gt;$c,<br />

		));<br />

	}<br />

<br />



<br />

<br />

<br />

<br />

Espero me puedas ayudar, Gracias