Luciano Nascimento
Luciano Nascimento

Reputation: 2600

Yii2: Model 'fields' ignore null values

Yii 2 Docs explains that I can set the fields that should be returned by default by toArray(). (http://www.yiiframework.com/doc-2.0/yii-base-model.html#fields()-detail)

Theres any possibility to ignore when contains null values?

function fields() {
    return [
        'email', // Ignore if email is null.
        'fullName', // Ignore if fullName is null.
    ];
}

Upvotes: 0

Views: 966

Answers (1)

MrRP
MrRP

Reputation: 822

Try this:

function field() {
    $return = [];
    if(!empty($this->email)) {
        $return[] = 'email';
    }
    if(!empty($this->fullName)) {
        $return[] = 'fullName';
    }
    return $return;
}

Upvotes: 1

Related Questions