Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Does Yii's Gii's CRUD generator take into account models' relations?

I used Yii's Gii's CRUD generator for a model that has a relation defined with another model, expecting that it would create some sort of dropdown or other way to select an instance of the related entity, but rather it just showed a regular textbox.

Is this the normal behavior of Gii or did I do something wrong?

This are the models and their relations:
Model Event: relation 'Venue' => array( self::BELONGS_TO, 'Venue', 'venue' )
Model Venue: relation 'Events' => array( self::HAS_MANY, 'Event', 'venue' )

I was expecting the Event CRUD to show some way of picking an instance of Venues.

like image 327
Petruza Avatar asked Dec 27 '22 06:12


1 Answers

That is just normal behaviour for Gii, when generating forms(for both CRUD and only forms), it makes all input fields textfields. So the default gii CRUD and form generator doesn't take relations into account while generating code.
We have to manually make changes to the view file, namely _form.php for the model in question, for you that is Event.
So for your requirement, you can make the following changes to that file :

/* As you have 'venue' field as the foreign key in the Event model */
<div class="row">
   <?php echo $form->labelEx($model, 'venue'); ?>
   <?php echo $form->dropDownList($model,'venue', CHtml::listData(Venue::model()->findAll(),
      'id', //this is the attribute name(of Venue model- could be the id of the venue) for list option values 
      'name' // this is the attribute name(of Venue model- could be the name of the venue) for list option texts 
    ); ?>
   <?php echo $form->error($model,'venue'); ?>

To make further changes/customizations read more about CActiveForm.
Hope this helps.

like image 130
bool.dev Avatar answered Jan 30 '23 22:01