1

I currently have a user field called field_reputation with a default integer value of 0 (if a user registeres).

enter image description here

The idea is that this field increases when certain actions are executed. For example, when a user publishes a new article, field_reputation should be its current value + 10.

I am trying to achieve this using a form hook:

function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'node_article_form') ) ) {
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_increase_reputation';
        }
      }
} 

And then this function is called:

function _increase_reputation(array &$form, FormStateInterface $form_state) {
  // Do something here
}

However I can't seem to figure out what code should be written in this function.

  • 2
    That should be done in hook_node_presave(), a submit handler is too late as the node is already saved – Clive Oct 30 '17 at 14:05
3

As @Clive says, form submit handler is a bit too late. Do it in hook_node_presave or hook_entity_presave. If you do it in hook_node_presave:

  1. Check the node type first: if ($node->bundle() === 'article')

  2. Get the current user: $user = User::load(\Drupal::currentUser()->id());

  3. Then set the field value: $value = (int) $user->get('field_reputation')->getString() + 10; $user->set('field_reputation', $value); (I'm not 100% sure on this code, but I'm sure there are better ways to do it when you have more than 5 minutes :D. Feels dirty to use getString() and then type-cast it into int)

  4. Save the user entity with $user->save();

If you use hook_entity_presave then you just need to check for the entity type additionally: $entity->getEntityType->Id() === 'node'

|improve this answer|||||
  • Thanks for your reply! Could you help me out a little more? I am quite newby at Drupal... I tried using the following code: jsfiddle.net/6bst99ut/1. But it does not work, nor gives me any errors. – Rubenxfd Oct 30 '17 at 15:15
  • Any updates? :) – Rubenxfd Oct 31 '17 at 8:54
  • @Rubenxfd, if you're putting that code in mytheme.theme, it might not work. Create a new module and put that code in the .module file. Also make sure you put use \Drupal\user\Entity\User at the top of the module file. – Beebee Oct 31 '17 at 9:54
  • I have tried adding a custom module like you said, but provided code does nothing :( – Rubenxfd Oct 31 '17 at 12:59
  • Did you enable your custom module? – Beebee Oct 31 '17 at 13:04

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.