Eutherpy
Eutherpy

Reputation: 4571

Get model from ID in Yii

I want to change what is shown in my yii2 app's history view, so that I don't show a person's ID but his first and last name.

This is a part of my data grid

        [
                'attribute' => 'oldPerson.Id',
                'label' => Yii::t('app', 'Previously In Charge'), 
                'value' => function($model){                   
                    return $model->person->FirstName . ' ' . $model->person->LastName; }              
        ],

but this isn't good since my $model is a history object, which contains a person's ID. I somehow need to obtain the entire person object based on that ID, but I don't know how.

This is my Person model:

namespace app\models;

use Yii;
use \app\models\base\Person as BasePerson;

/**
 * This is the model class for table "person".
 */
class Person extends BasePerson
{
public $created_at;
public $created_by;
public $updated_at;
public $updated_by;
public $id;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return array_replace_recursive(parent::rules(),
        [
            [['FirstName', 'LastName', 'Title', 'CitizenNumber', 'Employment', 'Contact'], 'required'],
            [['FirstName'], 'string', 'max' => 20],
            [['LastName'], 'string', 'max' => 40],
            [['Title'], 'string', 'max' => 50],
            [['CitizenNumber'], 'string', 'max' => 13],
            [['Employment', 'Contact'], 'string', 'max' => 100],
            [['CitizenNumber'], 'unique']
        ]);
    }
}

Upvotes: 1

Views: 8256

Answers (2)

Anoop Saini
Anoop Saini

Reputation: 307

its also working fine

$model=Modelname::findOne($id);

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133360

Normally you can get the model based on id this way

public function findModel($id)
{
    if (($model = Person ::findOne($id)) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

$model contain the Person info related to $id

Upvotes: 2

Related Questions