1

This question is refining the poorly asked Is there any easy way to set the default author for a node being edited to the current author if it is currently anonymous?

The site I'm working on has a lot of Anonymous nodes because it is a migration from a system that didn't have a proper user system. Users can claim their articles (they have permission via the override node options module) by going in and editing the node and changing the system author.

I'd like the default value on the edit form for node owner to be the current user for non-admin users who are editing a node that was not owned by anyone previously. I'm sure it must be imminently doable through some form alter or form preprocess hook, but I don't quite get the drupal form system yet. Solutions and pointers to good sources of information both welcome. My ulterior motive in this question is to learn more about how to use hook_form_alter to change the values of fields on the form, and particularly the owner field, so answers related to that are preferred.

1

You can do this pretty quickly in a custom module by implementing a hook_form_alter().

In this example, I created a module called "anon" (you might want to use something more specific) and in my anon.module, I have the following:

<?php

/**
 * Implements hook_form_alter()     
 */
function anon_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "article_node_form" && isset($form['author']['name']['#default_value']) && $form['author']['name']['#default_value'] == "") {
    $form['author']['name']['#default_value'] = $user->name;
  }
}

The above code checks to see if you are on a article_node_form (change this to the content type you are using), if the author of the form is blank (which is representative of an anonymous user) and then sets the author name to the currently logged in user name.

Note that by default a new form will always set the author value to the logged in user, so this would only apply for existing nodes.

  • That is great, and exactly what I was looking for. A few changes to check for role and adjustments to target the node forms I'm dealing with and I'm off to the races. Thanks! This example is just what I need to get me going with other modifications to the form too. Thanks! – UltraBob Nov 8 '16 at 2:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.