Search code examples
apostrophe-cms

Create and join a piece to a user (of a particular group) upon user creation in Apostrophe CMS


The site I'm building contains user profiles that I've set up as pieces that joinByOne to a user. Right now, the creation of the profile piece and the join to the user are a manual process but I need to automate that process.

Upon creation of a user (in a particular group) I need to:

  1. Create a new instance of a profile piece
  2. Assign that piece to the newly created user
  3. Redirect that user to an edit form view of their profile piece (which should also occur upon subsequent successful logins of the user)

Upon trash of a user of this privileged group I need to:

  1. Trash any associated profile piece

Upon rescue from trash of a user of this privileged group I need to:

  1. Rescue any associated profile piece from the trash

How do I do this?


Solution

  • You can write an afterInsert method for your project level lib/modules/apostrophe-users, in which you insert a profile piece by invoking the insert API of your profiles module.

    To create a join between them, I'd suggest a joinByOne relationship from the profile back to the user. If the join field is called _user and idField is set to userId, then you can preset this relationship by setting the userId property to the _id of the user when you maker the insert call.

    As for the trash, users have afterTrash and afterRescue methods waiting for you to override them.

    This HOWTO contains more details about how to work with the model layer.