Yii Framework Forum: Obtaining Data From Another Table Cgridview Widget - Yii Framework Forum

Jump to content

  • (2 Pages)
  • +
  • 1
  • 2
  • You cannot start a new topic
  • You cannot reply to this topic

Obtaining Data From Another Table Cgridview Widget Have data from a column from another table show up in CGridView widget Rate Topic: ***** 1 Votes

#21 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 18 March 2013 - 01:48 PM

Your _partial_view would look something like

<?php foreach ($data->targets as $target):?>
	<div class="drug-target">
		<?php echo "{$target->id}: {$target->name}";?>
	</div>
<?php endforeach; ?>


Matt
0

#22 User is offline   Tanya_new_2_yii 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 44
  • Joined: 10-March 13

Posted 19 March 2013 - 12:05 PM

Hello Matt,
Thank you again for the reply!

I tried implementing this, and got a white screen with only 1 row, and still have nothing under the target column.

Attached File  changes.png (5.11K)
Number of downloads: 10

Tanya

//Drug.php (model)

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(
			'targets' => array(self::MANY_MANY, 'Target', 'Drug_has_target(drug_id, target_id)')
		);
	}

public function targetsToString()
{
    $targets = $this->targets;
    if ($targets) 
        {
        $string = '';
        foreach($targets as $target) {
            $string .= $targets->target_id . ', ';
        }
        return substr($string,0,strlen($string)-1);
    }
    return null;
}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'drug_name' => 'Drug Name',
			'drug_id' => 'Drug ID',
			
		);
	}



//Admin.php (for Drug)
<?php $this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'drug-targets-grid',
        'dataProvider'=>$model->search(),
        'filter'=>$model,
        'columns'=>array(
                'drug_id',
                'drug_name',
                array(
                        'header' => 'Targets',
                        'value' => '$data->targetsToString()'
                ),
                array(
                        'class'=>'CButtonColumn',
                ),
        ),
)); ?>



View Postwaterloomatt, on 18 March 2013 - 01:34 PM, said:

No, you've done everything correctly but you've run into the problem le_top and I were discussing. To display the names of the targets add this to your Drug model

public function targetsToString()
{
    $targets = $this->targets;
    if ($targets) 
	{
        $string = '';
        foreach($targets as $target) {
            $string .= $targets->name . ', ';
        }
        return substr($string,0,strlen($string)-1);
    }
    return null;
}

and modify your grid to this:

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'drug-targets-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'id',
		'name',
		array(
			'header' => 'Targets',
			'value' => '$data->targetsToString()'
		),
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>

Please see my earlier post about how to cleanly get around this limitaion.

Matt

0

#23 User is offline   Tanya_new_2_yii 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 44
  • Joined: 10-March 13

Posted 19 March 2013 - 12:18 PM

Just wondering where (in what file) to add the PHP code that you provided (I'm guessing that it would be in the Drug model page)?

I read the post that you referred me to, I am thinking that I will add the following within the code for the widget (parts I am unsure of are in CAPS);

//Admin.php
<?php $this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'drug-targets-grid',
        'dataProvider'=>$model->search(),
        'filter'=>$model,
        'columns'=>array(
                'drug_id',
                'drug_name',
                array(
                        'header' => 'Target ID',
                        value'=>'$this->grid->getTARGET()->renderPartial(\'_viewTARGET_ID\', array(\'data\'=>$data),true);', 
                ),
                array(
                        'class'=>'CButtonColumn',
                ),
        ),
)); ?>





View Postwaterloomatt, on 18 March 2013 - 01:48 PM, said:

Your _partial_view would look something like

<?php foreach ($data->targets as $target):?>
	<div class="drug-target">
		<?php echo "{$target->id}: {$target->name}";?>
	</div>
<?php endforeach; ?>


Matt

0

#24 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 19 March 2013 - 10:39 PM

//Admin.php
<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'drug-targets-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'drug_id',
		'drug_name',
		array(
			'header' => 'Target ID',
			'type' => 'raw',
			'value'=>'$this->grid->getOwner()->renderPartial("_drug_target", array("data"=>$data), true);', 
		),
		array(
			'class'=>'CButtonColumn',
		)
	)
)); ?>

// $this->grid->getOwner() returns the owner (usually a controller) of the grid. Then, we're using the controller to render a partial view of the 'targets' relation.

// _drug_target is the name of the partial view file to render. I've created and attached it to this post; drop it in the same folder and the grid. (views/drug ??)
// We're passing a $data object (Drug model) to the view and then looping over it's 'targets' relation

http://www.yiiframew...-clistview/#hh1

Matt

Attached File(s)


0

#25 User is offline   Tanya_new_2_yii 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 44
  • Joined: 10-March 13

Posted 20 March 2013 - 06:24 AM

Hello Matt,

Thank you for the explanation of how the partial view works. I just made the changes, and I still get the white screen with only the 1st result showing up (for drug_id and drug_name), and nothing under the results column.

Tanya


View Postwaterloomatt, on 19 March 2013 - 10:39 PM, said:

//Admin.php
<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'drug-targets-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'drug_id',
		'drug_name',
		array(
			'header' => 'Target ID',
			'type' => 'raw',
			'value'=>'$this->grid->getOwner()->renderPartial("_drug_target", array("data"=>$data), true);', 
		),
		array(
			'class'=>'CButtonColumn',
		)
	)
)); ?>

// $this->grid->getOwner() returns the owner (usually a controller) of the grid. Then, we're using the controller to render a partial view of the 'targets' relation.

// _drug_target is the name of the partial view file to render. I've created and attached it to this post; drop it in the same folder and the grid. (views/drug ??)
// We're passing a $data object (Drug model) to the view and then looping over it's 'targets' relation

http://www.yiiframew...-clistview/#hh1

Matt

0

#26 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 20 March 2013 - 07:41 AM

K - please post your models (Drug & Target), controller (DrugController) and view files. I'll take a look.

Thanks,

Matt
0

#27 User is offline   Tanya_new_2_yii 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 44
  • Joined: 10-March 13

Posted 20 March 2013 - 08:11 AM

OK THANK YOU (I really appreciate it)!! I have attached the files.
Sorry for all the trouble,
Tanya

*I had tried the relatedbehavior function yesterday too (also had an empty target column), and so you'll see this commented out in the Drug model file.

View Postwaterloomatt, on 20 March 2013 - 07:41 AM, said:

K - please post your models (Drug & Target), controller (DrugController) and view files. I'll take a look.

Thanks,

Matt

Attached File(s)


0

#28 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 20 March 2013 - 12:49 PM

Hi,

I got everything up and running. Had to make a few tweaks to the models. I've attached the entire app + SQL file. At this point, I would guess that there is something not right with the database. For example, the link table Drug_has_targets isn't being populated. Can you confirm there are records in the table for the drug/targets? Also, I noticed that the drug_id (Drug model) and target_id (target_model) have required validators. This is the default behavior when creating models with Gii but I usually remove them from the required list because they are usually setup as primary auto-increment keys in the DB. Are you manually entering their Ids into the create/update forms? And are they setup correctly as primary keys?
Attached File  medicine-app.jpg (61.47K)
Number of downloads: 10
Attached File  medicine.zip (326.57K)
Number of downloads: 6
-- 
-- Structure for table `drug`
-- 

DROP TABLE IF EXISTS `drug`;
CREATE TABLE IF NOT EXISTS `drug` (
  `drug_id` int(11) NOT NULL AUTO_INCREMENT,
  `drug_name` varchar(100) NOT NULL,
  `drug_indication` varchar(1700) NOT NULL,
  `drug_synonym` varchar(120) NOT NULL,
  `drug_brand` varchar(40) NOT NULL,
  PRIMARY KEY (`drug_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- 
-- Data for table `drug`
-- 

INSERT INTO `drug` (`drug_id`, `drug_name`, `drug_indication`, `drug_synonym`, `drug_brand`) VALUES
  ('1', 'Test', 'Test', 'Test', 'Test');

-- 
-- Structure for table `target`
-- 

DROP TABLE IF EXISTS `target`;
CREATE TABLE IF NOT EXISTS `target` (
  `target_id` int(11) NOT NULL AUTO_INCREMENT,
  `target_name` varchar(70) NOT NULL,
  PRIMARY KEY (`target_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- 
-- Data for table `target`
-- 

INSERT INTO `target` (`target_id`, `target_name`) VALUES
  ('1', 'target1'),
  ('2', 'target2');

-- 
-- Structure for table `drug_has_target`
-- 

DROP TABLE IF EXISTS `drug_has_target`;
CREATE TABLE IF NOT EXISTS `drug_has_target` (
  `drug_id` int(11) NOT NULL,
  `target_id` int(11) NOT NULL,
  PRIMARY KEY (`drug_id`,`target_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- 
-- Data for table `drug_has_target`
-- 

INSERT INTO `drug_has_target` (`drug_id`, `target_id`) VALUES
  ('1', '1'),
  ('1', '2');

Cheers,

Matt
0

#29 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 20 March 2013 - 12:54 PM

Also the _drug_target.php file you attached has an error in it. Sorry, if I sent it that way before.

<?php foreach ($data->targets as $target):?>
	<div class="drug-target">
		<?php echo $target->target_id?. ': '. $target->target_name;>
	</div>
<?php endforeach; ?>

// Notice this line: <?php echo $target->target_id?. ': '. $target->target_name;>
<?php foreach ($data->targets as $target):?>
	<div class="drug-target">
		<?php echo $target->id . ': '. $target->name;?>
	</div>
<?php endforeach; ?>

The app I sent you has all the correct files.

Matt
0

#30 User is offline   Tanya_new_2_yii 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 44
  • Joined: 10-March 13

Posted 21 March 2013 - 08:14 AM

Hello Matt,

Thank you for fixing the issue - I will try to get this set-up (I'm a complete newbie, so this may take a while). For the drug and target tables I can confirm that there are records as I can see the records in PHPmyadmin, and the csv files from which I am loading my tables with are filled with entries. I am not sure about the id's in the DB create/update forms, so I guess I am not manually entering them :S. I have set the following though in my DB ..I am assuming that my primary keys are correctly set ..

Drug table -> PK = drug_id
Target table -> PK = target_id
Drug2target table -> drug_id = index -> FK to Drug table
target_id = index -> FK to Target table

Tanya

View Postwaterloomatt, on 20 March 2013 - 12:49 PM, said:

Hi,

I got everything up and running. Had to make a few tweaks to the models. I've attached the entire app + SQL file. At this point, I would guess that there is something not right with the database. For example, the link table Drug_has_targets isn't being populated. Can you confirm there are records in the table for the drug/targets? Also, I noticed that the drug_id (Drug model) and target_id (target_model) have required validators. This is the default behavior when creating models with Gii but I usually remove them from the required list because they are usually setup as primary auto-increment keys in the DB. Are you manually entering their Ids into the create/update forms? And are they setup correctly as primary keys?
Attachment medicine-app.jpg
Attachment medicine.zip
-- 
-- Structure for table `drug`
-- 

DROP TABLE IF EXISTS `drug`;
CREATE TABLE IF NOT EXISTS `drug` (
  `drug_id` int(11) NOT NULL AUTO_INCREMENT,
  `drug_name` varchar(100) NOT NULL,
  `drug_indication` varchar(1700) NOT NULL,
  `drug_synonym` varchar(120) NOT NULL,
  `drug_brand` varchar(40) NOT NULL,
  PRIMARY KEY (`drug_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- 
-- Data for table `drug`
-- 

INSERT INTO `drug` (`drug_id`, `drug_name`, `drug_indication`, `drug_synonym`, `drug_brand`) VALUES
  ('1', 'Test', 'Test', 'Test', 'Test');

-- 
-- Structure for table `target`
-- 

DROP TABLE IF EXISTS `target`;
CREATE TABLE IF NOT EXISTS `target` (
  `target_id` int(11) NOT NULL AUTO_INCREMENT,
  `target_name` varchar(70) NOT NULL,
  PRIMARY KEY (`target_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- 
-- Data for table `target`
-- 

INSERT INTO `target` (`target_id`, `target_name`) VALUES
  ('1', 'target1'),
  ('2', 'target2');

-- 
-- Structure for table `drug_has_target`
-- 

DROP TABLE IF EXISTS `drug_has_target`;
CREATE TABLE IF NOT EXISTS `drug_has_target` (
  `drug_id` int(11) NOT NULL,
  `target_id` int(11) NOT NULL,
  PRIMARY KEY (`drug_id`,`target_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- 
-- Data for table `drug_has_target`
-- 

INSERT INTO `drug_has_target` (`drug_id`, `target_id`) VALUES
  ('1', '1'),
  ('1', '2');

Cheers,

Matt

0

#31 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 21 March 2013 - 08:33 AM

K- it is also critical to confirm there are records in the link table.
0

#32 User is offline   Tanya_new_2_yii 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 44
  • Joined: 10-March 13

Posted 21 March 2013 - 11:15 AM

Hi Matt,

I was able to get it running - AND IT WORKS!!!

Thank you SO much for your help ...you're a genius!

Tanya

View Postwaterloomatt, on 21 March 2013 - 08:33 AM, said:

K- it is also critical to confirm there are records in the link table.

0

#33 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 21 March 2013 - 11:35 AM

Quote

you're a genius!

I've been called names before, but never that.
0

Share this topic:


  • (2 Pages)
  • +
  • 1
  • 2
  • 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