0

I have a content type "Application". And "Site Administrator" and "Developer" users are allowed to add it.

If logged-in user is "Site Administrator", the value of "Author" field will be the reference of other content type. So, in the respective field table,

entity_type : node, bundle : {content-type-name}

If logged-in user is "Developer". I'd like to save current logged-in user id as the value of "Author" field.

entity_type : user, bundle : user

How could I get it with drupal?

Thanks in advance.

1 Answer 1

0
  1. The "author" field would be a User Reference field.
  2. You can use hook_form_alter to limit this fields allowed $options to be either the logged in user, or the list of users of Developers.

Something similar too ...

function MYMODULE_hook_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'node_add_application') {
    if (in_array('Developer', $user->roles)) {
      // Set the default value of the author field to the logged in users uid.
      $form['field_AUTHOR_FIELDNAME']['options']['#default_value'] = $user->uid;
    }
    if (in_array('Site Administrator', $user->roles)) {
      // Overwrite the general users list with UIDs only of a specific role.

      // Get uids of a specific role.
      $query = 'SELECT DISTINCT(ur.uid) 
          FROM {users_roles} AS ur
          LEFT JOIN roles r on ur.rid = r.rid
          WHERE r.name = :role';
      $result = db_query($query, array(':role' => 'Developer'));
      foreach ($result as $row) {
        $developer_uids[] = $row->uid;
      }
      foreach ($form['field_AUTHOR_FIELDNAME']['options'] as $uid => $label) {
        if (!in_array($uid, $developer_uids)) {
          unset($form['field_AUTHOR_FIELDNAME']['options'][$uid];
        }
      }
    }
  }
}

This is a rough example of the logic and code it would take to alter the select list of user names for the author field to either default to the logged in developer, or show "site admins" only developers.

I have written such code before, this exact code is only an example based upon the details given in your question. It is un-tested.

2
  • i misread a portion of your question. But you can still do this with entity references. You still do this with hook_form_alter you just change 1 condition to make an option list of entity ids for that type...
    – tenken
    Commented Nov 24, 2012 at 6:25
  • Instead of doing 2 different entity types. I prefer your way. Thanks for the help.
    – user8887
    Commented Nov 29, 2012 at 3:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.