I want to create one new model class, which will be extended in all other class. I want to auto set some fields when admin is addind/editing any record. i.e. createdDate, createdIp, updatedDate, updatedIp..etc.
Now my issue all fields will not be common in all models. So i want to check if object has createdDate property then only set it's value. If there will be no condition and model has not createdDate member then it will generate error. Below is code what i am trying. But it is not working.
public function beforeSave()
{
if(isset($this->createdDate))
die('this model have createdDate field');
else
die('this model does not have createdDate field');
}
Model may not straight forward, it may extend database table related class automatically. Below is printed object. createdDate field is in private list.
If i am using var_dump(property_exists($this, 'createdDate'));
it is giving me false.
AdvertisementRate Object
(
[bannerLocation_search] =>
[bannerType_search] =>
[_md:private] => CActiveRecordMetaData Object
(
[tableSchema] => CMysqlTableSchema Object
(
[schemaName] =>
[name] => tbl_advertisement_rate
[rawName] => `tbl_advertisement_rate`
[primaryKey] => advertisementRateId
[sequenceName] =>
[columns] => Array
(
[createdDate] => CMysqlColumnSchema Object
(
[name] => createdDate
[rawName] => `createdDate`
[allowNull] =>
[dbType] => datetime
[type] => string
[defaultValue] =>
[size] =>
[precision] =>
[scale] =>
[isPrimaryKey] =>
[isForeignKey] =>
[autoIncrement] =>
[_e:private] =>
[_m:private] =>
)
Please help me to add this logic.
yes.. CActiveRecord is extended to my class.
MasterAdmin.php
class MasterAdmin extends CActiveRecord
{
public function beforeSave()
{
echo '<pre>';
var_dump(property_exists($this, 'createdDate'));
exit;
}
}
User.php
class User extend MasterAdmin
{
// So whenever any record added or edited, beforeSave will be called and i can autoset createddate value.
}
Are you using activerecord?
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#hasAttribute-detail
property_exists()
is what you're looking for.
This way, if the property exists but is set to NULL
, the above function will return true as you would expect, while isset()
would return a false leading you to believe the property does not exist.
Works for me. See example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With