• Development

    Storing First and Last Name with Social API for Drupal 8

    I recently worked on a project that relied on Social API for Google, Facebook, and Yahoo authentication. Out of the box everything worked great. Our site stores the user’s first name and last name in two fields on the user entity: field_first_name  and field_last_name. There are a few ways to tap into the Social API authentication process (which comes from the Social Auth component).

    Originally we leveraged the SocialAuthEvents::USER_CREATED event in an event subscriber. We set the first name and last name, then re-saved the user. This, however, executes after the user is created. The issue we had was that we also have Salesforce integration and both name fields are required in Salesforce. When the user is first saved it was pushing to Salesforce without the name fields, which triggered an error.

    The solution was to implement a different event handler: SocialAuthEvents::USER_FIELDS

    This lets you manipulate the user fields before the user is saved. I poked through the Social Auth code and figured out how to get the first and last name values. Here’s the working solution:

    web/modules/custom/mymodule/mymodule.services.yml

    web/modules/custom/mymodule/src/EventSubscriber/MymoduleSocialAuthSubscriber.php

    After creating/updating the files above, just clear the caches and test.