registration_field.rdoc

doc/guides/registration_field.rdoc
Last Update: 2020-06-30 15:06:09 -0700

Add new field during account creation

The create account form only handles login and password parameters by default. However, you might want to ask for additional information during account creation, such as requiring the user to also enter their full name or their company's name.

A) Accounts table

Let's assume you wanted to wanted to store the additional field(s) directly on the accounts table:

atler_table :accounts do
  add_column :name, String
end

You need to override the create-account template, which by default in Rodauth you can do by adding a create-account.erb template in your Roda views directory.

Once you've added the create-account.erb template, and had it include a field for the name, you can handle the submission of that field in a before create account hook:

plugin :rodauth do
  enable :login, :logout, :create_account

  before_create_account do
    # Validate presence of the name field
    unless name = param_or_nil("name")
      throw_error_status(422, "name", "must be present")
    end

    # Assign the new field to the account record
    account[:name] = name
  end
end

B) Separate table

Alternatively, you can store the additional field(s) in separate table, for example:

create_table :account_names do
  foreign_key :account_id, :accounts, primary_key: true, type: :Bignum
  String :name, null: false
end

You can then handle the new submitted field as follows:

plugin :rodauth do
  enable :login, :logout, :create_account

  before_create_account do
    # Validate presence of the name field
    throw_error_status(422, "name", "must be present") unless param_or_nil("name")
  end

  after_create_account do
    # Create the associated record
    db[:account_names].insert(account_id: account[:id], name: param("name"))
  end

  after_close_account do
    # Delete the associated record
    db[:account_names].where(account_id: account[:id]).delete
  end
end