Reputation: 43
Well, I found this, but i can't see the relation with my error.. I am newbie--well I know this excuse is unacceptable but i try to find the solution first before i ask it here. I hope you can help me.
so I have this code, i put this code in views :
foreach ($budget as $budget):
if (array_key_exists('year', $_GET)) {
$criteria = new CDbCriteria;
$criteria->condition = 'year = ' . $_GET['year'];
$criteria->addCondition('mapping_id = '. $budget->id);
$yearBudget = YearlyBudget::model()->find($criteria);
} else {
$yearBudget = new YearlyBudget;
}
endforeach;
and then after that code, i simply echo this :
echo $yearBudget->budget;
then i got non-object error. I just don't understand and stuck in this code. Please help, and thank you.
print_r($yearBudget); :
YearlyBudget Object(
[_new:CActiveRecord:private] =>
[_attributes:CActiveRecord:private] => Array
(
[id] => 1
[mapping_id] => 1
[year] => 2012
[budget] => 2000000
[balance] => 2000000
[created] => 2013-11-20 10:16:29
[updated] =>
)
[_related:CActiveRecord:private] => Array
(
)
[_c:CActiveRecord:private] =>
[_pk:CActiveRecord:private] => 1
[_alias:CActiveRecord:private] => t
[_errors:CModel:private] => Array
(
)
[_validators:CModel:private] =>
[_scenario:CModel:private] => update
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
Ah, sorry if my english is bad..
Upvotes: 3
Views: 9977
Reputation: 9979
Check whether the object is empty or not before you access it's attribute.
if($yearBudget){
echo $yearBudget->budget;
}else{
echo "No Yearly Budget with given criteria";
}
If you are not getting desired result, check the conditions carefully
$criteria->condition = 'year = ' . $_GET['year'];
$criteria->addCondition('mapping_id = '. $budget->id);
Upvotes: 1
Reputation: 3781
I strongly advice using CHtml::value()
method http://www.yiiframework.com/doc/api/1.1/CHtml#value-detail
echo CHtml::value($yearBudget, 'budget');
this is ivery handy when it comes to multiple related object, and you do not need to check out every related model existence to access its attributes
echo CHtml::value($budget, 'company.fiscalYear.creator.id');
Upvotes: 2
Reputation: 7265
you need to make sure you have a valid model after trying to find it with your criteria :
foreach ($budget as $budget):
if (array_key_exists('year', $_GET)) {
$criteria = new CDbCriteria;
$criteria->condition = 'year = ' . $_GET['year'];
$criteria->addCondition('mapping_id = '. $budget->id);
if(YearlyBudget::model()->exists($criteria)) // check if this exists
$yearBudget = YearlyBudget::model()->find($criteria);
else
$yearBudget = new YearlyBudget; // or throw an exception or something
} else {
$yearBudget = new YearlyBudget;
}
endforeach;
Upvotes: 0