1

我有一个带有图像字段的内容类型。用户可以创建内容并上传图像。我不想用户在上传图像后更改/删除图像,但仍会在节点编辑表单上显示图像。所以我只需要从图像字段中禁用/删除“删除”按钮。我尝试了以下方法(通过 hook_form_alter),但没有奏效:

$form['field_image']['#disabled'] = TRUE;

下面的作品,但它完全隐藏了图像元素,这不是我所追求的:

$form['field_image']['#access'] = FALSE;

请帮助找到解决方法。

4

2 回答 2

5

您必须使用hook_field_widget_form_alter函数并在其中使用 dpm() 查找变量详细信息,然后使用Forms API中的属性更改按钮。

但我建议让小部件字段在编辑表单上只读,而不是删除删除按钮。

// Hide remove button from an image field
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // If this is an image field type
  if ($context['field']['field_name'] == 'MY_FIELD_NAME') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element
      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
  //dpm($element);
  // Hide the remove button
  $element['remove_button']['#type'] = 'hidden';

  // Return the altered element
  return $element;
}

有用的问题:

于 2013-09-11T11:47:44.137 回答
1

您也可以使用 hook_form_alter 和 after_build 函数

// hook_form_alter implementation
function yourmodule_form_alter(&$form, $form_state, $form_id) {
    switch ($form_id)  {
        case 'your_form_id':
            $form['your_file_field'][LANGUAGE_NONE]['#after_build'][] = 'yourmodule_hide_remove_button';
            break;
    }
}

// after_build function
function yourmodule_hide_remove_button($element, &$form_state) {
    // if multiple files are allowed in the field, then there may be more than one remove button.
    // and we have to hide all remove buttons, not just the one of the first file of the field
    // 
    // Array
    // (
    //    [0] => 0
    //    [1] => 1
    //    [2] => #after_build
    //    [3] => #field_name
    //    [4] => #language
    //    [5] => ...
    // )
    //
    // the exemple above means we have 2 remove buttons to hide (2 files have been uploaded)

    foreach ($element as $key => $value){
        if (is_numeric($key)){
            unset($element[$key]['remove_button']);
        } else break;
    }

    return $element;
}
于 2014-09-25T09:12:02.363 回答