0

On my drupal site, using the User module, I have added extra fields to the user registration form such as 'Organization'. I notice that this has created a mysql database called 'user__field_organization'.

I am trying to write a custom module which involves creating new users.

At the moment my module creates a new user, with a username, password and email. The code for this (which works fine) is:

$user_data = ['name' => 'John', 'mail' => '[email protected]', 'pass' => 'examplePassword','status' => 1,]; 

$this->user = $this->user_store->create($user_data);

(where $this->user_store = $etm->getStorage('user'); )

But I also need to update the extra fields such as Organization but can't work out how to do this.

I have looked at this question: How to programmatically create new user with custom fields?

And I have tried adding custom_field_organization or user__field_organization into $user_data but it doesn't work.

I have been trying to find out where in the User module a user is created once the registration form is submitted. If I could find that then I could copy what is done there.

1
  • 1
    You should be able to set that just using field_organization. If that doesn't work (it should though), you can set the value by doing things like $user->field_organization = $value. You can see the machine name of the fields in the configuration page for the user entity. Nov 27, 2019 at 18:14

1 Answer 1

1

You are close to the right solution. You have to add 'field_organization' => 'some_value' to your $user_data array.

They keys in the $user_data array is the field names. The field name is what comes after user__ in the table name. You can also see the field name in the UI where you add the fields (it’s also called machine name).

Your Answer

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

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