Showing related data in a column in Gridview

I have a Jobs model that hasMany JobItems. Is it possible to fetch the related JobItems in the Jobs view and display, for example, the JobItem description and its related Status in one of the columns of my Job view’s gridview?

I know the syntax for getting the info in straight PHP can be done with a foreach ($model->JobItems as $JobItem) and then echoing, say, $JobItem->product->status to get the value, but I can’t quite wrap my brain around how this could be done in a gridview.

Any help will be immensely appreciated!

You can use an annomous function





[

  'attribute' => '',

   'value' => function ($model) {

   	return your information;

   },

],



A better way would be to create a get function in your model




//model


public function getJobDetails() {

 if (is_array($this->jobItems)) {

  foreach ($this->jobItems as $jobItem) {

   echo 'Desc:' . $jobItem->product->desc . ' Status: ' . $jobItem->product->status;

  }

 } else {

  return Yii::$app->formatter->nullDisplay;

 }

}//in your grid 

'columns'=>[

 'jobDetails'

]



Hi, thanks so much for the guidance - it’s working, but both ways of doing this are resulting in the job items being echoed prior to the gridview being rendered.

Inside the cell where the items should be appearing, the gridview is rendering the “not set” text (probably because it’s registering null values).

Here’s my code in the model:




	public function getJobDetails() {

	 if (is_array($this->jobItems)) {

	  foreach ($this->jobItems as $jobItem) {

	   echo $jobItem->product->product . ' - ' . $jobItem->upholstery->upholstery."<br>";

	  }

	 } else {

	  return Yii::$app->formatter->nullDisplay;

	 }

	}



And in the view (both ways you suggested, they both do the exact same thing)




[

'attribute' => 'Items',

'value' => 'jobDetails',

],

[

  'attribute' => '',

   'value' => function ($model) {

	foreach ($model->jobItems as $jobItem) {

		echo $jobItem->product->product . ' - ' . $jobItem->upholstery->upholstery."<br>";

	}

   },

],



I’ve attached a screenshot to demonstrate this odd behaviour.

Any advice anyone can offer to overcome this strange result would be most welcome.

Answering my own question here because I figured it out.

The function needs to [font="Courier New"]return [/font]the string, not [font="Courier New"]echo[/font] it.

Sharing the fixed code in case it helps someone else.




	public function getJobDetails() {

		$output = '';

	 if (is_array($this->jobItems)) {

	  foreach ($this->jobItems as $jobItem) {


	   $output.=$jobItem->product->product . ' - ' . $jobItem->upholstery->upholstery."<br>";

	  }

	  return $output;

	 } else {

	  return Yii::$app->formatter->nullDisplay;

	 }

	}