Displaying related data in views

Hello,

I am completely new to Yii and I started with some tutorials to understand the framework. I did build up CRUD pages with Gii and I want to show on the index.php related data from another database table. So in my case I have an ‘Area’ and this Area has some ‘Rocks’. In the database the Rocks foreign key ‘rocks_area_id’ has a relation to ‘area_id’. Also in Yii the relation has been set:

models/Rocks.php

public function getRocksArea()

{


    return $this->hasOne(Areas::className(), ['area_id' => 'rocks_area_id']);


}

models/Areas.php

public function getRocks()

{


    return $this->hasMany(Rocks::className(), ['rocks_area_id' => 'area_id']);


}

So in the form of views/rocks/_form.php I have the following code:

<?= $form->field($model, ‘rocks_area_id’)->dropDownList(ArrayHelper::map(Areas::find()->all(), ‘area_id’, ‘area_name’)) ?>

And when I want to display the ‘area_name’ I always get the error message ‘Class ‘Areas’ not found’! But this class has been defined (class Areas extends \yii\db\ActiveRecord) and also in this class there is the relation to the Rocks defined with the function getRocks().

So if someone can help me with that?

Thank you in advance!

Your call to Area::find makes it look for the Area model class. You could add


use app\models\Area;

to the form page. Using Array Helper in the drop down code is just one way of providing the options, all it really needs is an array with keys and values which could be as simple as


['Yes'=>'Yes', 'No'=>'No']

, or some complex method in the model of the form, called by


$model->yourMethodName()

.