Reputation: 2418
I have a model, $userModel
. I want to check if any of the fields for this model are empty or null
.
At the moment I am doing it with a big if statement.
if(!empty($userModel->name) && !empty($userModel->address) ... && !empty($userModel->email))
{
// All fields have values
}
This way works, but if later I need to add another field to the model, then I need to go back to the if and add another &&
condition there.
How can I do this in one check?
Is there something like: $userModel::model()->areAllFieldsFilled();
Extra info: The model is already saved in the db, and there is no need for user input. This is just me checking how complete a particular model is, by no means will all these fields be required in the database, only a few. Things like $userModel->bio
are usually left null
.
I want to avoid checking 5 to 10 fields. I don't want a giant if that has to be maintained when the model changes.
Upvotes: 4
Views: 3638
Reputation: 17051
I think you don't need do it.
Everything you need - it just specify your validation rules.
For example:
<?php
class Brand extends CActiveRecord
{
public function tableName()
{
return 'brand';
}
public function rules()
{
return [
['name, country', 'on' => 'insert'],
['name', 'type', 'type' => 'string', 'on' => 'insert'],
['name', 'length', 'max' => 100, 'on' => 'insert'],
['name', 'type', 'type' => 'array', 'on' => 'search'],
['country', 'type', 'type' => 'string'],
['country', 'length', 'max' => 50],
];
}
}
When you will use this model you'll just need validate this model by $model->validate()
and if it fails - show errors with $model->getErrors()
. Moreover you can specify what rules scenario you wish to use. For example: $model->senario = 'search';
will be used validation rule search
and property name
should be array. But when scenario insert
name should be string with length not more than 100.
In my example fields: name, country - required for insert (['name, country', 'on' => 'insert']
).
Upvotes: -1
Reputation: 31739
Use empty()
if(!empty($userModel->name)) { .. }
Update
$modelData = array($userModel->name, $userModel->address, $userModel->email);
if(!in_array('', $modelData) && !in_array(null, $modelData)) { .. }
Or you can use array_intersect
-
if(empty(array_intersect(array('', null), $modelData))) { .. }
Upvotes: 0
Reputation: 310983
PHP allows you to iterate over an object's properties. The check for each property could be simplified using empty():
$allHaveValues = TRUE;
foreach ($userModel as $key => $value) {
if (empty($value)) {
$allHaveValues = FALSE;
break;
}
}
if ($allHaveValues) {
// Do something...
}
Upvotes: 4