Yii Framework Forum: Load Reccords On Update From 2 Models On Same _Form - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Load Reccords On Update From 2 Models On Same _Form Rate Topic: -----

#1 User is offline   gunnit 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 49
  • Joined: 08-June 12

Posted 01 March 2013 - 11:27 AM

Hello everybody thanks for reading.
I have a little issue .
I have _form.php file that i use to collect data that is saved in 2 different tables. Plz Reffer below for example.
On the update page however only the records from one table get loaded.
I wanted to know how can i load the reccords from the other table on the update page.
Controler Update Function :
public function actionUpdate($id) {
        $model = $this->loadModel($id);

        if (isset($_POST['UserRegistry'])) {
            //THIS SAVES THE USER ON THE USER TABLE
            $user = new User;
            $user->user_name = $_POST['UserRegistry']['user_name'];
            $user->password = $_POST['UserRegistry']['password'];
            $user->role = $_POST['UserRegistry']['role'];
            $user->save(false);
           
            $model->attributes = $_POST['UserRegistry'];
            $model->id_user = $user->id_user;
            if ($model->save())

            //SAVE THE USERS TO THE CHOSEN GROUP
                $groups = $_POST['UserRegistry']['groups'];
            if (!empty($groups)) {

                foreach ($groups as $group) {
                    $bridge = new BridgeGroup();
                    $bridge->id_user_registry = $model->id_user_registry;
                    $bridge->id_group = $group;
                    $bridge->save(false);
                }
            }


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

On the model =
public $user_name;
public $password;
public $role;
On the _form.php
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
	'id'=>'user-registry-form',
	'enableAjaxValidation'=>true,
)); 

?>

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

       
        
                <?php 
//THIS IS INSERTED ON THE CURRENT TABLE
echo $form->textFieldRow($model,'firstname',array(
                    'class'=>'span10',
                    'maxlength'=>45,
                    'hint'=>__('The First Name of the participant.'),
                    'prepend'=>'<i class="icon-text-width"></i>',
                    )); ?>

               
     
         <?php 
//THIS IS INSERTED INTO THE USER TABLE
echo $form->textFieldRow($model,'user_name',array(
                'class'=>'span10',
                'hint'=>__('Login username of the contact being inserted'),
                'prepend'=>'<i class="icon-user"></i>',
                'maxlength'=>45,
                'autocomplete'=>'off'
                )); ?>
     </div>
      ...........


When i update this i only get the first name loaded and the user_name dose not load. Any help or tips will help me a lot. Thanks in advanced
0

#2 User is offline   macinville 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 268
  • Joined: 25-October 10
  • Location:Marikina City, Philippines

Posted 01 March 2013 - 11:36 AM

You have to define another model in your controller and pass it to your view. Please post the models involved and their relationship so I can provide a more productive answer.
Tell your tail.
Don't be shy to upvote a post if it was able to help you
0

#3 User is offline   gunnit 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 49
  • Joined: 08-June 12

Posted 01 March 2013 - 12:50 PM

View Postmacinville, on 01 March 2013 - 11:36 AM, said:

You have to define another model in your controller and pass it to your view. Please post the models involved and their relationship so I can provide a more productive answer.

Sure would be awsome if you can help out
User Registry Model
<?php

/**
 * This is the model class for table "{{user_registry}}".
 *
 * The followings are the available columns in table '{{user_registry}}':
 * @property integer $id_user_registry
 * @property string $firstname
 * @property string $lastname
 * @property string $company
 * @property integer $postcode
 * @property string $city
 * @property string $state
 * @property string $country
 * @property string $addressstreet
 * @property string $email
 * @property string $email2
 * @property integer $tel
 * @property integer $fax
 * @property integer $cel
 * @property string $notes
 * @property string $creation_date
 * @property integer $id_user
 * @property integer $company_role
 * @property integer $group
 */
class UserRegistry extends CActiveRecord
{
        public $user_name;
        public $password;
        public $role;
        public $confirmpassword;
        public $groups;
        const ROLE_PRI = 4;
        const ROLE_MEM = 5;
        
        
/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return UserRegistry 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 '{{user_registry}}';
	}

	/**
	 * @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('postcode, tel, fax, associate, role, cel, id_user, group', 'numerical', 'integerOnly'=>true),
			array('firstname, lastname, company, city, state, country, user_name, password, confirmpassword', 'length', 'max'=>45),
			array('addressstreet, email, email2, company_role', 'length', 'max'=>255),
			array('notes', 'length', 'max'=>455),
			array('creation_date, groups', 'safe'),
                        array('email','email'),
                        array('email2','email'),
                        array('email', 'unique'),
                        array('email2', 'unique'),
                        array('creation_date','default',
                                            'value'=>new CDbExpression('NOW()'),
                                            'setOnEmpty'=>false,
                                            'on'=>'insert'),
                        array('creation_date','default',
                                            'value'=>new CDbExpression('NOW()'),
                                            'setOnEmpty'=>false,
                                            'on'=>'update'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id_user_registry, groups, firstname, lastname, company, postcode, city, state, country, addressstreet, email, email2, tel, fax, cel, notes, creation_date, id_user, company_role, group', '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(
                    'groupsB' => array(self::MANY_MANY, 'Group', 'tbl_bridge_group(id_user_registry, id_group)'),
                    'idUser' => array(self::BELONGS_TO, 'User', 'id_user'),
                    // 'bridgeGroups' => array(self::HAS_MANY, 'BridgeGroup', 'id_user_registry'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id_user_registry' => __('Id User Registry'),
			'firstname' => __('First Name'),
			'lastname' => __('Last Name'),
			'company' => __('Company'),
			'postcode' => __('Postcode'),
			'city' => __('City'),
			'state' => __('State'),
			'country' => __('Country'),
			'addressstreet' => __('Street Address'),
			'email' => __('Email'),
                        'email2' => __('Second Email'),
			'tel' => __('Tel'),
			'fax' => __('Fax'),
			'cel' => __('Cel'),
			'notes' => __('Notes'),
			'creation_date' => __('Creation Date'),
			'id_user' => __('User Login'),
                        'company_role' => __('Company Role'),
                        'group' => __('Group'),
                        'user_name'=>'User Name',
                        'password'=>'Password',
                        'groups'=>__('Groups'),
                        'role'=>__('Privileges'),
                        'associate'=>__('Alternate')
                    
		);
	}

	/**
	 * 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_user_registry',$this->id_user_registry);
		$criteria->compare('firstname',$this->firstname,true);
		$criteria->compare('lastname',$this->lastname,true);
		$criteria->compare('company',$this->company,true);
		$criteria->compare('postcode',$this->postcode);
		$criteria->compare('city',$this->city,true);
		$criteria->compare('state',$this->state,true);
		$criteria->compare('country',$this->country,true);
		$criteria->compare('addressstreet',$this->addressstreet,true);
		$criteria->compare('email',$this->email,true);
                $criteria->compare('email2',$this->email2,true);
		$criteria->compare('tel',$this->tel);
		$criteria->compare('fax',$this->fax);
		$criteria->compare('cel',$this->cel);
		$criteria->compare('notes',$this->notes,true);
		$criteria->compare('creation_date',$this->creation_date,true);
		$criteria->compare('id_user',$this->id_user);
                $criteria->compare('company_role',$this->company_role);
                $criteria->compare('group',$this->group);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
         public function getRoleOptions(){
            return array(
                        
                        self::ROLE_PRI => Lookup::item('role', self::ROLE_PRI),
                        self::ROLE_MEM => Lookup::item('role', self::ROLE_MEM)
                );
        }
}

User Model
<?php

/**
 * This is the model class for table "tbl_user".
 *
 * The followings are the available columns in table 'tbl_user':
 * @property integer $id_user
 * @property integer $role
 * @property string $user_name
 * @property string $password
 * @property string $last_login_date
 * @property string $email
 * @property string $tel
 *
 * The followings are the available model relations:
 * @property TblEventLog[] $tblEventLogs
 * @property TblLicensee[] $tblLicensees
 */
class User extends CActiveRecord {

    public $confirmPassword;

    const ROLE_ADMINISTRATOR = 0;
    const ROLE_CA = 1;
    const ROLE_GI = 2;
    const ROLE_USR = 3;
    const ROLE_PRI = 4;
    const ROLE_MEM = 5;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User 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 '{{user}}';
    }

    /**
     * @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('role, user_name, password, confirmPassword', 'required'),
            array('role, id_user_registry', 'numerical', 'integerOnly' => true),
            array('user_name, password, email, tel', 'length', 'max' => 45),
            array('last_login_date, full_name', 'safe'),
            array('user_name', 'unique'),
            array('user_name', 'length', 'min' => 3),
            array('user_name', 'length', 'max' => 45),
            array('email', 'email'),
            array('confirmPassword', 'compare', 'compareAttribute' => 'password'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id_user, role, user_name, password, last_login_date, email, tel', '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(
            'tblProjects' => array(self::HAS_MANY, 'TblProject', 'id_user'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id_user' => 'Id User',
            'role' => 'Role',
            'user_name' => 'User Name',
            'password' => 'Password',
            'last_login_date' => 'Last Login Date',
            'email' => 'Email',
            'tel' => 'Tel',
            'confirmPassword' => 'Confirm Password',
            'full_name' => 'Full Name',
            'id_user_registry' => 'id user registry',
        );
    }

    /**
     * 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_user', $this->id_user);
        $criteria->compare('role', $this->role);
        $criteria->compare('user_name', $this->user_name, true);
        $criteria->compare('last_login_date', $this->last_login_date, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('tel', $this->tel, true);
        $criteria->compare('full_name', $this->full_name, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                    'pagination' => array(
                        'pagesize' => 100,),
                ));
    }

    public function validatePassword($password) {
        return $this->hashPassword($password) == $this->password;
    }

    public function hashPassword($password) {
        return md5($password);
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            $this->password = $this->hashPassword($this->password);
            return true;
        } else {
            return false;
        }
    }

    public function updateLoginDate() {
        $this->last_login_date = date('Y-m-d H:i:s');
        $this->save(false, array('last_login_date'));
    }

    public function getRoleOptions() {
        return array(self::ROLE_ADMINISTRATOR => Lookup::item('role', self::ROLE_ADMINISTRATOR),
            self::ROLE_CA => Lookup::item('role', self::ROLE_CA),
            self::ROLE_GI => Lookup::item('role', self::ROLE_GI),
            self::ROLE_USR => Lookup::item('role', self::ROLE_USR),
            self::ROLE_PRI => Lookup::item('role', self::ROLE_PRI)
        );
    }

}

0

#4 User is offline   macinville 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 268
  • Joined: 25-October 10
  • Location:Marikina City, Philippines

Posted 01 March 2013 - 08:20 PM

In your controller, you should add something like this:
$model = $this->loadModel($id)
$user = $model->idUser;//load the user model related to your user registry id


then pass the $user model to your view:
$this->render('update',array(
	'model'=>$model,
	'user'=>$user
));


in your view>update file, use the appropriate models
//THIS IS INSERTED INTO THE USER TABLE
//use $user instead of $model because `user_name` belongs to $user
echo $form->textFieldRow($user,'user_name',array(
     'class'=>'span10',
     'hint'=>__('Login username of the contact being inserted'),
     'prepend'=>'<i class="icon-user"></i>',
     'maxlength'=>45,
     'autocomplete'=>'off'
)); ?>


Feel free to play around the result of this. When saving, you have to use $_POST[User] instead of $_POST[UserRegistry] when necessary. I'll leave it you as a mental exercise :P

And just a tip mate: avoid posting all the content of your codes here if not necessary,because it makes your post too long (actually, avoid posting a long post if not needed). I'm one of those many lazy posters that gets sleepy when seeing loooooooooong strings of text :P. It also discourages getting good answers from other busy forum members.
Tell your tail.
Don't be shy to upvote a post if it was able to help you
0

#5 User is offline   gunnit 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 49
  • Joined: 08-June 12

Posted 04 March 2013 - 05:40 AM

View Postmacinville, on 01 March 2013 - 08:20 PM, said:


And just a tip mate: avoid posting all the content of your codes here if not necessary,because it makes your post too long (actually, avoid posting a long post if not needed). I'm one of those many lazy posters that gets sleepy when seeing loooooooooong strings of text :P. It also discourages getting good answers from other busy forum members.


Thanks for the help and the advice , absolutely right , i usualy dont but i got lazy too .... You were kind enough to give me an answer so thanks and il be more concise in the future
0

#6 User is offline   macinville 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 268
  • Joined: 25-October 10
  • Location:Marikina City, Philippines

Posted 08 March 2013 - 10:26 PM

:)
Tell your tail.
Don't be shy to upvote a post if it was able to help you
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

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