Assigning Data To User

Hi,

I am having two table tbl_user & tbl_customer.

tbl_customer consists of customer information & data.

tbl_user contains staffs users to manage customer data.

Suppose there are 50 customer’s in tbl_customer, i want to assign first 10 customer’s to user1 so that when user1 logins he will see the 10 customers which are assigned to his id.

Similarly the next 10 customer’s is assigned to user2, so that when user2 logins he will see the 10 customers which are assigned to his id.

admin user can see all the data which is assigned to all user.

Can anyone please guide me how can i do this.

Do you want to store this against the session ( not recommended, with auto login this will be stored in the cookie ), or do you want to make this dynamic?

Does this work for you?




 <?php

   // your call

   Yii::app()->user->getCustomers();



if so, do this:

If you haven’t already, create a CWebUser override file. Example: /components/MyWebUser.php

Put the following in it ( sort of pseudo code, please use your own judgement for your app );




<?php


class MyWebUser extends CWebUser{

 public $customers;


 public function getCustomers(){

  if( $this->customers !== null )

    return $this->customers;


  $this->customers = Customers::model()->findAllByAttributes(array(

   'condition' => 'CUSOMTER_ID',  // you could actually do something more complex with CDBCriteria

   'limit' => 10

  ));


   return $this->customers;

 }

 

}



In your main.cfg do the following




	'components'=>array(

            'user'=>array(

                    'class'=>'MyWebUser',

                    'allowAutoLogin'=>true, // enable cookie-based authentication

            ),



This basically loads your user component override where you can attach any functions you’d like to against it. This will not store it against the session and is my recommended way of doing it. There is a different method of overriding CUserIdentity to store against the session.

Hi notsoluckycharm,

thanks for your reply,

The resolution which you have provided is something different what I wanted.

What I require is as below,

admin user logins, he goes to cgridview page, there he sees all the data of the customer’s.

In front of all the data I want a checkbox to select the data and an assign to button on the admin page.

I will select the data and click on assign to button, after clicking on assign to button, it will provide me the list of users from tbl_user table. I will select the user and click on OK button. After that the selected data will be shown in his page when the user logins.

Thanks for reading

Please provide me some solution on this.

Dear all,

Can anyone please guide me, or provide me any useful link.

Dear Sanjay

I hope the following is helpful in your scenario.

To simulate your scenario, I have created three tables.

1.user (Model:User)

2.customer (Model:Customer)

3.user_customer (Model:UserCustomer)

Short Summary of what I have done.

[color="#000080"]1.Created a table user_customer with columns user_id and cust_id.It was left empty.

user_id refers to user.id and cust_id refers to customer.id.

  1. admin.php in /views/userCustomer will contain following elements.

    1.user gridview with checkbox column.

    2.customer gridview with checkbox column.

    3.form to create UserCustomer.

    4.userCustomer gridview.

  2. When admin checks a row in usergrid, user_id is dynamically updated in the form.

    Sameway when admin checks rows in customer-grid, customer field is dynamically updated in the form.

  3. When admin submits the form, userCustomer-grid is dynamiclly updated with new values.

  4. Modified the action userCustomer/index in such a way that it displays only customers associated with particular

    user.

6.Modified loginUrl to redirect the user to userCustomer/index.

[/color]

[color="#2F4F4F"]Kindly go through the following code blocks.[/color]

UserCustomer.php




<?php

class UserCustomer extends CActiveRecord

{       public $customers;


	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	public function tableName()

	{

		return 'user_customer';

	}


	

	public function rules()

	{

		

		return array(

			array('user_id, cust_id', 'required'),

			array('cust_id', 'unique'),

			array('user_id, cust_id', 'numerical', 'integerOnly'=>true),

			array('id,user_id, cust_id,customers', 'safe', 'on'=>'search'),

		);

	}




	public function relations()

	{

		return array(

			'customer' => array(self::BELONGS_TO, 'Customer', 'cust_id'),

			'user' => array(self::BELONGS_TO, 'User', 'user_id'),

		);

	}


	

	public function attributeLabels()

	{

		return array(

			'id' => 'ID',

			'user_id' => 'User',

			'cust_id' => 'Customer',

		);

	}


	

	public function search()

	{

		

		$criteria=new CDbCriteria;

                $criteria->with=array('user','customer');

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

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

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

		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

			'sort'=>array('attributes'=>array(

			'user_id'=>array('asc'=>'user.username','desc'=>'user.username DESC'),

			'cust_id'=>array('asc'=>'customer.name','desc'=>'customer.name DESC'),'*'

			)),

		));

	}

}




UserCustomerController.php




public function actionCreate()

{   

   if(Yii::app()->request->getIsAjaxRequest()&&isset($_POST['UserCustomer']))

   {

         $user=$_POST['UserCustomer']['user_id'];

         $customers=$_POST['UserCustomer']['customers'];

         $customers=explode(',',$customers);

         foreach($customers as $customer)

                 {

			 $model=new UserCustomer;

			 $model->user_id=$user;

			 $model->cust_id=$customer;

			 if($model->validate())

			    $model->save(false); //already validated.

	        }

         

            

     }

}


public function actionAdmin()

	{

		$user=new User('search');

		$customer=new Customer('search');

		$userCustomer=new UserCustomer('search');

		$user->unsetAttributes();  

		$customer->unsetAttributes();  

		$userCustomer->unsetAttributes();  

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

			$user->attributes=$_GET['User'];

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

			$customer->attributes=$_GET['Customer'];

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

			$userCustomer->attributes=$_GET['UserCustomer'];


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

			'user'=>$user,

			'customer'=>$customer,

			'userCustomer'=>$userCustomer,

		));

	}


public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('UserCustomer',array(

		'criteria'=>array('condition'=>'user_id='.Yii::app()->user->id),

		));

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

			'dataProvider'=>$dataProvider,

		));

	}




views/userCustomer/admin.php




<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'user-grid',

	'dataProvider'=>$user->search(),

	'filter'=>$user,

	'columns'=>array(

		'id',

		'username',

		'password',

		'email',

		'status',

		array(

			'class'=>'CButtonColumn',

		),

		array(

			'class'=>'CCheckBoxColumn',

			'selectableRows'=>1  //allows to check only one row.

		),

	),

)); ?>


<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'customer-grid',

	'dataProvider'=>$customer->search(),

	'filter'=>$customer,

	'columns'=>array(

		'id',

		'name',

		array(

			'class'=>'CButtonColumn',

		),

		array(

			'class'=>'CCheckBoxColumn',

			'selectableRows'=>2 //allows to check multiple rows.

		),

	),

)); ?>


<div class="wide form">


<?php $form=$this->beginWidget('CActiveForm'); ?>


	<div class="row">

		<?php echo $form->label($userCustomer,'user_id'); ?>

		<?php echo $form->textField($userCustomer,'user_id',array('id'=>'user')); ?>

	</div>


	<div class="row">

		<?php echo $form->label($userCustomer,'customers'); ?>

		<?php echo $form->textField($userCustomer,'customers',array('id'=>'customers')); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::button('Save',array('id'=>'butt')); ?>

	</div>


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


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

<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'user-customer-grid',

	'dataProvider'=>$userCustomer->search(),

	'filter'=>$userCustomer,

	'columns'=>array(

		'id',

		array(

		'name'=>'user_id',

		'value'=>'$data->user->username'),

		array(

		'name'=>'cust_id',

		'value'=>'$data->customer->name'),

		array(

			'class'=>'CButtonColumn',

		),

	),

)); ?>




<?php

Yii::app()->clientScript->registerScript('getUser','

$("body").on("change","#user-grid input[type=\"checkbox\"]",function(){

	var checked=$("#user-grid").yiiGridView("getChecked","user-grid_c6");

	$("#user").val(checked);

	});




');


Yii::app()->clientScript->registerScript('getCustomer','

$("body").on("change","#customer-grid input[type=\"checkbox\"]",function(){

	var checked=$("#customer-grid").yiiGridView("getChecked","customer-grid_c3");

	$("#customers").val(checked);

	});




');


Yii::app()->clientScript->registerScript('assignCustomer','

$("body").on("click","#butt",function(){

	$.ajax({

		type:"POST",

		url:"'.Yii::app()->createUrl('userCustomer/create').'",

		data:$(".wide form").serialize(),

		success:function(data){

		$("#user-customer-grid").yiiGridView("update",{

			data:{"UserCustomer[user_id]":$("#user").val()}});

		}

		

		});

	return false;

	});




');




In SiteController::actionLogin




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

		{

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

			if($model->validate() && $model->login())

				$this->redirect(Yii::app()->createUrl('userCustomer/index'));

		}



[color="#000080"][b]

In admin.php we have registered three scripts.[/b][/color]




Yii::app()->clientScript->registerScript('getUser','

$("body").on("change","#user-grid input[type=\"checkbox\"]",function(){

	var checked=$("#user-grid").yiiGridView("getChecked","user-grid_c6");

	$("#user").val(checked);

	});




');



Here "user-grid_c6" indicates the checkbox column is the seventh column in the grid.

Whenever admin checks a row , textfield for the user_id is updated with row id.




Yii::app()->clientScript->registerScript('getCustomer','

$("body").on("change","#customer-grid input[type=\"checkbox\"]",function(){

	var checked=$("#customer-grid").yiiGridView("getChecked","customer-grid_c3");

	$("#customers").val(checked);

	});




');



Here "customer-grid_c3" indicates the checkbox column is the fourth column in the grid.

Whenever admin checks a row or multiple rows , textfield for the customer is updated with all the row ids.




Yii::app()->clientScript->registerScript('assignCustomer','

$("body").on("click","#butt",function(){

	$.ajax({

		type:"POST",

		url:"'.Yii::app()->createUrl('userCustomer/create').'",

		data:$(".wide form").serialize(),

		success:function(data){

		$("#user-customer-grid").yiiGridView("update",{

			data:{"UserCustomer[user_id]":$("#user").val()}});

		}

		

		});

	return false;

	});




');




This script creates records for UserCustomer model from the form, when it is submitted by AJAX request.

During the same time it dynamically updates the userCustomer-grid with available records in the table. for the particular user.

Finally what we have acheived?

On a same page, we can allot the customers for a particular user and delete a customer for particular user.

Thus we can finetune our assignment.

Regards.

Hi seenivasan,

Thanks for your valuable time and effort you have taken to resolve my issue.

I will check and let you know.

Thanks again.

Hi seenivasan,

Sorry for the late reply, actually i was trying your code from so many days but not able to get it working.

I am still learning YII, so unable to understand it, though you have provided with good explanation.

I am having a customer table called tbl_customer where customer information resides and staff user table called tbl_user to manage customer data.

Model customer




public function attributeLabels()

	{

		return array(

			'name' => 'Name',

			'id' => 'ID',

			'username' => 'username'

			'password' => 'Password',

			'email' => 'Email',

			'lead_assigned_to' => 'Lead Assigned To',

			'package' => 'Package',

			'registration_date' => 'Registration Date',

			'lead_remarks' => 'Lead Remarks',

		);

	}



Model user




public function attributeLabels()

	{

		return array(

			'id' => 'ID',

			'username' => 'Username',

			'password' => 'Password',

			'email' => 'Email',

			'remarks' => 'Remarks',

		);

	}



Every day new customer gets register and that entry gets listed in alldata.php in cgridview.

in tbl_user there is admin user also who is have access to alldata.php and for other user’s

there is a page called mydata.php which will list the customer data in cgrid view assigned to the user by admin.

in alldata.php there will be dropdown menu which will list the user’s from tbl_user and a button called Assign.

admin user will select the data with the checkbox option and then select the user to whom he wants the data to assign and click on assign button.

After clicking on Assign button the selected data will be removed from the current page (alldata.php) and then gets listed in the mydata.php page of that user. Similarly it applies for the remaining data also.

I have not created any foreign key for this, does the above scenario requires foreign key?

Can you please help me in this.

Thanks in advance.

Hi,

I have managed to create a checkbox and dropdown list user on the alldata.php page by adding the below code in alldata.php.




<?php $form=$this->beginWidget('CActiveForm'); ?>


	<div class="row"> 

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

        <?php echo $form->dropDownList($model,'lead_assigned_to', CHtml::listData(User::model()->findAll(), 'username', 'username'), array('empty'=>'Please Select'));?> 

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

    </div>


......


<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'customer-grid',

	'dataProvider'=>$model->search(),

	'filter'=>$model,




	'columns'=>array(


		  array( 

                        'class'=>'CCheckBoxColumn', 

                        'selectableRows'=>2 //allows to check multiple rows. 

                ), 

Can anyone please help me in getting the below things done.

admin user will select the data with the checkbox option and then select the user to whom he wants the data to assign and click on assign button.

After clicking on Assign button the selected data will be removed from the current page (alldata.php) and then gets listed in the mydata.php page of that user. Similarly it applies for the remaining data also.

Thanks in advance

Hi,

Anyone please.

Thanks in advance

Hi,

Can anyone please guide me or provide me some reference document or link regarding this.

Thanks in advance.