Drush: 快速新增、刪除,更新或複製欄位 (Fields)

嘩!要弄 10 多個相同的欄位,只是標籤名 (Label) 不同,難道要手動一個一個新增嗎?Google Google 還真的沒有現成工具?真想罵髒話!幸好還沒有罵出來就想到 Drush,還真的能打救一命。

基本的欄位操作:新增、更新、刪除,複製及列出欄位資料都有提供,雖然功能上還有點遜,但能應付一般需求。用起來很簡單,在此不詳談。用 "drush help" 看看實例便懂,要是不明,不仿留言,會獨立回應你 :)

好的,工具有了,要試一試是否可行 (Drupal 最糟糕是這點,不試一試真假未知)。結果有點失敗... 就是.....DRUSH 內置並不支援自定 LABEL,真糟糕!才開心起來又要失望?

唉,嘗試打開程式碼看看吧 ...不負己望,給我輕易找到:

/*
 * File: drush\commands\core\field.drush.inc
 */
function drush_field_create($bundle) {
  $entity_type = drush_get_option('entity_type', 'node');
  
  $args = func_get_args();
  array_shift($args);
  if (empty($args)) {
    // Just one item in this array for now.
    $args[] = drush_field_create_wizard();
  }
  
  // Iterate over each field spec.
  foreach ($args as $string) {
 // list($name, $type, $widget) = explode(',', $string);
    list($label, $name, $type, $widget) = explode(',', $string); // 參數在這裏,輕輕動動,讓可接納親愛的 Label 小姐
    $info = field_info_field($field_name);
    if (empty($info)) {
      // Field does not exist already. Create it.
      $field = array(
        'field_name' => $name,
        'type' => $type,
      );
      drush_op('field_create_field', $field);
    }
    
    // Create the instance.
    $instance = array(
      'label' => $label, // 是的,不要忘記這也要貼 Label,出了問題就給人當山寨貨
      'field_name' => $name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
    );
    if ($widget) {
      $instance['widget'] = array('type' => $widget);
    }
    drush_op('field_create_instance', $instance);
    
    $urls[] = url(_field_ui_bundle_admin_path($entity_type, $bundle) . '/fields/' . $name, array('absolute' => TRUE));
  }
  drush_print(implode(' ', $urls));
}

以你所見,這裏也很簡單,只要動到 field_create_field & field_create_instance,還想要增加支援些什麼,API 一下看看相關說明。

寫下您的回覆

電子郵件不會公開