CDetailView with Relations

Hi,

I want to display all attributes from a model with the related attributes, but it doesn’t work.

Model:




public function relations()

{

    return array(

        'image' => array(self::HAS_MANY, 'Image', 'data_id'),

    );

}



Controller:




public function actionView($id)

{

    $modelData=$this->loadModel($id);

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

        'modelData'=>$modelData,

    ));

}



View:




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

    'data'=>$modelData,

    'attributes'=>array(

        'id',

	'title',

	'description',

	'create_date',

        'image.image',

    ),

)); ?>



Output:




ID: 1

Title: aaa

Description: aaa

Create Date: 2012-08-29 20:50:48

Image: Not set



Image is an related attribute, but it is "Not set".

Who can help me, please?

Thanks a lot.

Motte

If your image relation correctly represents your db scheme, it will return an array (of models), so you won’t be able to display image.image like that. Either target one of the array elements, or build a method that will return the data you need.

Hope it helps

PS You may want to search in the forum. It’s a frequent situation.

is data_id populated with a value from the Image model (FK from image table)? If not, then you will be pulling null so it will show as ‘not set’.

Hi,

Thanks for your replies.

The following code works:




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

	'data'=>$modelData,

	'attributes'=>array(

		'id',

		'title',

		'description',

		'create_date',

		'image.0.image', // Works, but looks like a workaround?

	),

)); ?>



But is this correct or is there a better solution? It looks like a little bit workaround.

Motte

Hi there,

I’d like to ask similar question. What if I need to display all the images associated with the given model (without knowing a priori their exact number) using CDetailView?

Is there a possibility different from writing a method that creates the required output?

Or there is possibility to iterate over data within CDetailView widget?