We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

how to tell if an attribute exists

hi,

I'm using $attribValue = $this->readAttribute(AppModel::FIELD); to get the value of this model/attribute.

If the field not exists, I have value is $attribValue = null, but the field, if exists, can contain null values too.

so ... how do I know if the field/attribute exists and what its value?

sorry for my english



4.0k
Accepted
answer
edited Jul '15

You can try override readAttribute($attribute) function in your model

For example:

public function readAttribute($attribute)
{
    if(!isset($this->{$attribute})) {
        return false; // or throw new \Exception("lore ipsum");
    }
    return parent::readAttribute($attribute);
}

or create model function hasAttribute

public function hasAttribute($attribute) {
    return (isset($this->{$attribute}));
}
edited Jul '15

that their approach is the best for me. thanks!!!

public function hasAttribute($attribute) {
    return (isset($this->{$attribute}));
}
edited Jul '15

Oopssssssssssss,

I marked you answer, but this question is not solved.

isset returns FALSE if the variable has been set to NULL.

in this case, I got false, because the variable occasionally can be NULL, like in the inserts, e.g.

sorry, but this queston is not solved...



4.0k
edited Jul '15

Yes :)

another solution

public function hasAttribute($attribute) {
    return $this->getModelsMetaData()->hasAttribute($this, $attribute);
}

Yesss

and this:

<?php
protected function hasAttribute($attribute)
{
    return $this->modelsMetadata->hasAttribute($this, $attribute);
}

or

<?php
protected function hasAttribute($attribute)
{
    $mm = $this->getModelsMetaData();
    return $mm->hasAttribute($this, $attribute);
}

what do you think?

thanks!!!