Jaeger Jaeger - 1 month ago 6
PHP Question

Is there a better way to write the following?

I got confronted with this "problem" several times already, I fix it the same way but I feel dirty just by thinking how I solved it.

Let's say I work with Drupal 8 and that I need to modify several select form's default value, "-Any-" by "Select...".

This is how I proceed each time :

if(isset($form['field_children_charge_value'])) {
$form['field_children_charge_value']['#options']['All'] = t('Select...');
}
if(isset($form['field_evolution_target_id'])) {
$form['field_evolution_target_id']['#options']['All'] = t('Select...');

}
// And so on


I feel bad writing like this, but, for my defense, I didn't have a lot of of PHP theory while learning, I directly got the practical courses.

an
elseif
expression would only work once since the first condition will match the pre requisite, and it won't bother checking if some other condition would work too.

I also got the problem once with javascript, and I did the same thing.

So, is there a better syntax, and if yes, what is it?

Answer Source

Been years since I coded in php, but this seems like a general "issue".
You can save all the fields in an array, and then use a for-each loop to execute the operation on each of them:

$fields = ["field1", "field2", "..."];

foreach($fields as $field) {
  if(isset($form[$field])) {
    $form[$field]['#options']['All'] = t('Select...');
  }
}