简体   繁体   English

有没有更好的方法来编写以下内容?

[英]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...". 假设我使用Drupal 8,并且需要通过“ Select ...”修改多个选择表单的默认值“ -Any-”。

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. 我的写作感觉很糟糕,但是,为了我的辩护,我在学习过程中没有太多的PHP理论,因此直接获得了实践课程。

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. elseif表达式仅会运行一次,因为第一个条件将与前提条件相匹配,并且它不会费心检查其他条件是否也会起作用。

I also got the problem once with javascript, and I did the same thing. 我也曾经用javascript遇到过问题,而且我做了同样的事情。

So, is there a better syntax, and if yes, what is it? 那么,有没有更好的语法,如果可以,它是什么?

Been years since I coded in php, but this seems like a general "issue". 自从我用php编码以来已有数年,但这似乎是一个普遍的“问题”。
You can save all the fields in an array , and then use a for-each loop to execute the operation on each of them: 您可以将所有字段保存在array中 ,然后使用for-each循环对每个字段执行操作:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM