Does the Yii Gii CRUD generator take model relationships into account?

I used the Yii Gii CRUD generator for a model that has a relationship defined with another model, expecting it to create some sort of drop-down list or other way to select an instance of the related object, but rather just show a regular text box.

Is this normal Gii behavior or am I doing something wrong?

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

I expected Event CRUD to show some way to select an instance of places.

+4
source share
2 answers

This is just the normal behavior for Gii, when creating forms (both for CRUD and only for forms), it does all the input field fields. Thus, the default gii generator and the form generator do not take relationships into account when generating the code.
We must manually make changes to the view file, namely _form.php for the model in question, this is an event for you.
Therefore, for your requirement, you can make the following changes to this 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'); ?> </div> 

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

+9
source

Use Giix, it works correctly for what you are looking for .. no manual changes are required.

+1
source

Source: https://habr.com/ru/post/1394824/


All Articles