Hi -
I am facing an issue that I am not able to fix. I have a workaround but I would be interested in understanding the root cause.
In my form I have multiple attributes but one of them is not displayed and populated in the controller like this:
Controller
public function actionCreate()
{
$walkthrough = new Walkthrough();
$post = new Post();
//Here is the device_id that I set in the controller and not in the form
$post->device_id = 3;
if ($walkthrough->load(Yii::$app->request->post()) && $post->load(Yii::$app->request->post()) && Model::validateMultiple([$walkthrough, $post])) {
$post->save(false);
$walkthrough->post_id = $post->id;
if ($walkthrough->save(false)){
$post->updateIndex(); <-- In this method I call a getter which uses the device_id
}
Model Post
public function getDevice()
{
return $this->hasOne(Device::className(), ['id' => 'device_id']);
}
[...]
public function updateIndex(){
$searchIndex = $this->searchIndex;
if (!isset($searchIndex)){
$searchIndex = new SearchIndex();
}
$searchIndex->title = $this->generatePermalink($this->title);
$searchIndex->summary = $this->summary;
$device = $this->device->description; <-- Error on this line
$searchIndex->device = $device;
$searchIndex->tags = $this->listTags;
$searchIndex->post_id = $this->id;
return $searchIndex->save();
}
I am getting the following error
2015-02-23 15:17:50 [38.121.179.140][2][-][error][yii\base\ErrorException:8] exception ‘yii\base\ErrorException’ with message ‘Trying to get property of non-object’ in /home/www/common/models/Post.php:293
Stack trace:
#0 /home/www/common/models/Post.php(293): yii\base\ErrorHandler->handleError(8, ‘Trying to get p…’, ‘/home/…’, 293, Array)
#1 /home/www/backend/controllers/WalkthroughController.php(131): common\models\Post->updateIndex()
The workaround is to set the device_id in the _form and then it works, I can access the $this->device->description
Question is, Am i missing something obvious or am I doing something wrong.
Please ask me for more details if needed, I am really interested in knowing the cause.
Thank you
–Matt