[solved]CGridView an a not filled related record

Hi Yii fans,

I’m building a flight application. In my flight model, I’ve defined two relations:




		return array(

			'pilote'=>array(self::BELONGS_TO, 'Annuaire','cdtbord'),

			'coPilote'=>array(self::BELONGS_TO, 'Annuaire','copilote'),

		);



In my flight model, cdtbord field is required but copilote not.

For a solo flight (no copilot), a new created row set copilote field to 0. That value has no related record in model Annuaire.

In my gridview for displaying the flights:




		array(               

		   	'header'=>'Co pilote',

		   	'type'=>'raw',

			'value'=>'$data->coPilote->nom_prenom',

			'filter'=>CHtml::activeDropDownList($model, 'copilote', CHtml::listData(Vol::model()->findAll(),'copilote','coPilote.nom_prenom'),array('prompt'=>'','class'=>'span3')),

		),



drop me an error saying "Trying to get property of non-object " while fetching the row with copilote field set to 0 … Not surprising in fact.

I’ve tried something like:




'value'=>'if($data->copilote!="0")$data->coPilote->nom_prenom',



no errors, but filled fields aren’t displayed at all …

Some help will be very appreciate.

Regards from France

Try:




'value'=>'($data->copilote!="0")?data->coPilote->nom_prenom:""',



Thank you for help, but this does not work.

unfortunately, it looks like the conditional statements aren’t evaluated.

Sorry!




'value'=>'($data->copilote!="0")?$data->coPilote->nom_prenom:""',



Dollar sign missing.

Conditional statements are evalueted, I used before.

If it isn’t the missing dollar sign. Maybe another problem, not the coditional statement, try:




'value'=>'(true)?"OK":"Not OK"',






'value'=>'(false)?"OK":"Not OK"',



Instead of


$data->copilote!="0" 

use


$data->coPilote!=null

This way you check if the relation coPilote has any value… and display the nom_prenom only when it does.




'value'=>'($data->copilote!="0")?$data->coPilote->nom_prenom:""',



Exact, I haven’t figured it out, and … hurra, it works.

Many thanks andredelorme

@mdomba, thank you for helping me.

default AR of flight model is to populate the copilote table with with a 0 value, so (well that’s how I understand it)


$data->coPilote!=null

is not working ("Trying to get property of non-object ")

Topic marked as [solved]

Why would you not make the copilote column nullable in your database and use null to represent a non-existant copilot?

That’s basically what null is for…

Hi,

that’s true, and finally, this is what I have done, using mdomba’s solution.

Regards from France.