Jump to content

Is it possible to add a field to a specific user role?


Recommended Posts

I understand how to add a field to users (regardless of role), however I would like to add a field that only is assigned to a specific user role.  Is this possible?

Couldn't find any information about this in the forums or documentation, so I'm resorting here to the forums.  Sorry if this is a repeat question.

Link to comment
Share on other sites

Hi jlahijani,

If you assign a field to a user template, then all users get that field.

Can you explain a bit more why you need this behaviour?

It would be easy to hide this particular field for all other roles with a hook.

Link to comment
Share on other sites

I would assign all the fields and just fill out the ones needed depending on the role.

Like I said, if you don't want the user to see the unecessary fields in the backend, you could hide them.

Maybe someone comes up with another solution, there are always multiple with Pw :)

Link to comment
Share on other sites

You're welcome.

Here's a good overview how Hook works: http://processwire.com/api/hooks/

Also checkout the captain which shows you all the hooks available: http://somatonic.github.io/Captain-Hook/

And here an example, written in the browser and not tested:

// Inside your autoload module you have installed...

public function init() {
  $this->addHookAfter('ProcessPageEdit::buildForm', $this, 'hideFields');
}

public function hideFields(HookEvent $event) {
  
  // Do nothing if we don't edit a user
  if ($this->page->template != 'user') return;
  
  // Get the form instance returned from the hooked method
  $form = $event->return;
  
  // Define fields to hide per role
  $hideFields = array(
    'role1' => array('field1', 'field40'),
    'role2' => array('field5', 'field2'),
  );
  
  // Hide the fields
  foreach ($hideFields as $role => $fields) {
    if ($this->user->hasRole($role)) {
      foreach ($fields as $field) {
        $f = $form->get($field);
        $f->collapsed = Inputfield::collapsedHidden;
      }    
    }
  }

  $event->return = $form;

}
  • Like 5
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...