简体   繁体   English

hook_form_alter根据用户的角色取消设置字段

[英]hook_form_alter to unset fields according to a user's role

I am facing a problem when I try to use hook_form_alter to hide fields according to user's roles. 当我尝试使用hook_form_alter根据用户的角色隐藏字段时,我hook_form_alter了问题。 I have used unset() and removed the field from the $form array, but it is still showing when the form is rendered. 我已经使用了unset()并从$form数组中删除了该字段,但是在呈现表单时它仍然显示。

Here is my code: 这是我的代码:

function mymodule_form_alter($form, $form_state, $form_id){
  global $user;
  if($form_id == 'my_content_type'){
    if(array_key_exists(5,$user->roles) && !array_key_exists(3,$user->roles)){
      if(empty($form_state['field']['args'][0]->title)){
        unset($form['field_body']);
      }
    }
  }
}

Instead of using unset() to hide a form element, you should set the #access property to FALSE . 您应该将#access属性设置为FALSE ,而不是使用unset()来隐藏表单元素。 This keeps the form build tree intact, which avoids problems if other modules try to access or alter that information. 这样可以保持表单构建树的完整性,从而避免在其他模块尝试访问或更改该信息时出现问题。 Source 资源

function MYMODULE_form_alter($form, $form_state, $form_id) {

  global $user;
  $account = $user;

  if ($form_id == 'MYCONTENTTYPE_node_form') {

    if (user_has_role(5, $account) && !user_has_role(3, $account)) {

      if (empty($form_state['field']['args'][0]->title)) {

        $form['field_body']['#access'] = FALSE;
      }
    }
  }
}

If this is still not working, double-check your if-requests. 如果仍然无效,请仔细检查您的if-requests。 Are they really doing something? 他们真的在做什么吗? Are you currently logged-in as a corresponding user? 您目前是否以相应的用户身份登录?

I have found the solution. 我找到了解决方案。 I need just added the & with $form and $form_state in hook_form_alter parameters. 我需要在hook_form_alter参数中添加&with $ form和$ form_state。 Like hook_form_alter(&$form, &$form_state, $form_id) 像hook_form_alter(&$ form,&$ form_state,$ form_id)

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

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