Yii Framework Forum: save multiple data from checkboxlist - project with gii generator - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

save multiple data from checkboxlist - project with gii generator save multiple data checkbox from user form - project with gii

#1 User is offline   matthewjara90 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 22-October 15

  Posted 22 October 2015 - 06:49 PM

Hola a todos los programadores, he creado un proyecto con Gii para generar los modelos y los controladores.
ADJUNTO EL PROYECTO AQUI:

DESEO DESDE EL FORMULARIO DE USUARIO PODER GUARDAR EN LA TABLA RELACION USUARIOS_IDIOMAS los idiomas pertenecientes a un usuario, muchisimas gracias... mas adelante expongo el codigo y las imagenes:

Mi base de datos es la siguiente:
-----------------
USUARIOS |
-----------------
id->PK |
nombre |
apellido |
documento |
direccion |
#id_genero->FK |
#id_profesion->FK |
-------------------


-------------------
GENEROS |
------------------
id->PK |
nombre |
------------------


-------------------
PROFESIONES |
------------------
id->PK |
nombre |
------------------

-------------------
IDIOMAS |
------------------
id->PK |
nombre |
------------------


-------------------
USUARIOS_IDIOMAS |
------------------
#id_usuarios->FK |
#id_idiomas->FK |
------------------








mi idea es que al momento de llenar el formulario para usuario, contenga los checkbox de idiomas, para saber qué idiomas maneja el usuario. Y por medio de esos checkbox guardar los registros en la tabla USER_LANGUAGE

pero realmente no se como hacer para que esto suceda.
Alguien me puede colaborar?


Model ---> Usuario.php

<?php

/**
 * This is the model class for table "usuarios".
 *
 * The followings are the available columns in table 'usuarios':
 * @property integer $id
 * @property string $nombre
 * @property string $apellido
 * @property string $documento
 * @property string $direccion
 * @property integer $idGenero
 * @property integer $idProfesion
 */
class Usuario extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Usuario the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'usuarios';
	}

	/**
	 * @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('nombre, apellido, documento, direccion, idGenero, idProfesion', 'required'),
			array('idGenero, idProfesion', 'numerical', 'integerOnly'=>true),
			array('nombre, apellido, direccion', 'length', 'max'=>250),
			array('documento', 'length', 'max'=>20),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, nombre, apellido, documento, direccion, idGenero, idProfesion', '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(

			'genero'=>array(self::BELONGS_TO,'Genero','idGenero'),
			'profesion'=>array(self::BELONGS_TO,'Profesion','idProfesion'),
			'idiomas'=>array(self::MANY_MANY,'Idioma', 'usuarios_idiomas(id_usuarios,id_idiomas)'),

		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'nombre' => 'Nombre',
			'apellido' => 'Apellido',
			'documento' => 'Documento',
			'direccion' => 'Direccion',
			'idGenero' => 'Id Genero',
			'idProfesion' => 'Id Profesion',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('nombre',$this->nombre,true);
		$criteria->compare('apellido',$this->apellido,true);
		$criteria->compare('documento',$this->documento,true);
		$criteria->compare('direccion',$this->direccion,true);
		$criteria->compare('idGenero',$this->nombre);
		$criteria->compare('idProfesion',$this->nombre);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
}






controller -> UsuarioController.php

<?php

class UsuarioController 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
		);
	}

	/**
	 * 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'),
				'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('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 Usuario;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Usuario']))
		{
			$model->attributes=$_POST['Usuario'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

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

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Usuario']))
		{
			$model->attributes=$_POST['Usuario'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$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)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$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'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Usuario');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Usuario('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Usuario']))
			$model->attributes=$_GET['Usuario'];

		$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 the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Usuario::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='usuario-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}







USUARIO FORM ---> form_.php

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'usuario-form',
	'enableAjaxValidation'=>false,
));


 ?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>

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

	<div class="row">
		<?php echo $form->labelEx($model,'nombre'); ?>
		<?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>250)); ?>
		<?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'=>250)); ?>
		<?php echo $form->error($model,'apellido'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'documento'); ?>
		<?php echo $form->textField($model,'documento',array('size'=>20,'maxlength'=>20)); ?>
		<?php echo $form->error($model,'documento'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'direccion'); ?>
		<?php echo $form->textField($model,'direccion',array('size'=>60,'maxlength'=>250)); ?>
		<?php echo $form->error($model,'direccion'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'Genero'); ?>
		<?php echo $form->radioButtonList($model,'idGenero', CHtml::listData(Genero::model()->findAll(),'id','nombre'), array('separator'=>' ','labelOptions'=>array('style'=>'display:inline'))); ?>
		<?php echo $form->error($model,'idGenero'); ?>
	</div>

	
	<div class="row">
		<?php echo $form->labelEx($model,'Idioma'); ?>
		<?php echo $form->checkBoxList($model,'id', CHtml::listData(Idioma::model()->findAll(),'id','nombre'), array('separator'=>' ','labelOptions'=>array('style'=>'display:inline'))); ?>
		<?php echo $form->error($model,'idIdioma'); ?>
	</div>
	

	<div class="row">
		<?php echo $form->labelEx($model,'Profesion'); ?>
		<?php echo $form->dropDownList($model,'idProfesion',CHtml::listData(Profesion::model()->findAll(),'id','nombre'),array('empty'=>'seleccione una profesión')); ?>
		<?php echo $form->error($model,'idProfesion'); ?>
	</div>

	<div class="row buttons">
		<?php echo CHtml::submitButton($model->isNewRecord ? 'Guardar' : 'Save'); ?>
	</div>

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

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






realmente no me guarda la seleccion del checkbox en la tabla relacion entre usuarios e idiomas... la webapp no genera ningun error pero no cumple con el requerimiento.

espero su pronta respuesta. muchas gracias

Attached File(s)


0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users