Cannot display related value in detailview

I’m absolutely new to yii so, please forgive my ignorance…

I have a test assignment to create a user list. I have a “anagrafica” table (people) and a “documenti” (different kinds of documents) . the db is set to link the “tipodocumento” (document type) of “anagrafica” table to the “id” field of the “documenti” table. I managed to create a dropdown lint in the _form.php file using a tutorial, so i suppose db tables are correctly linked. I simply want to display the “tipologia” field of the “documenti” table, but i apparently continue to get errors.

in the “anagrafica” controller i wrote this:

    public function getNomedocumento()
    {
        return $this->hasOne(Documenti::className(), ['id' => 'tipologia']);
    }

while in the view.php file for the anagrafica i have this

<?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'nome', 'cognome', 'eta', 'email:email', ['attribute'=>'tipodocumento','value'=>$model->nomedocumento->tipologia], ], ]) ?>

I’m currently getting this error message

Getting unknown property: app\models\Anagrafica::tipologia

If I understand correctly, you want to use the “tipodocumento” attribute of the Anagrafica model as the id of the Documenti table and display the “tipologia” attribute of Documenti for that id, correct? The function relating the tables would go in your Anagrafica model file. It would be slightly different than the one you have in your controller.

    public function getDocumenti()
    {
        return $this->hasOne(Documenti::className(), ['id' => 'tipodocumento']);
    }

This allows you to display $model->documenti->tipologia or $model->documenti->anyOtherFieldFromDocumenti

2 Likes