Drupal自定义用户注册表单

时间:2014-02-28 23:27:28

标签: drupal drupal-7 drupal-modules drupal-forms drupal-hooks

我使用module_form_alter钩子构建了一个自定义注册表单。我还使用db_add_field将所需的新字段添加到数据库中。现在我可以在用户注册/用户配置文件编辑中将值添加到表中,并且值也会存储在数据库中..但我无法做的是获取存储在数据库中的值在用户配置文件编辑表单中显示。是否有一个钩子可以在表单加载时将数据库中的值加载到表单中?或者还有其他方法吗?

 function customUser_schema_alter(&$schema) {
   // Add field to existing schema.
   $schema['users']['fields']['detail'] = array(
         'type' => 'varchar',
         'length' => 100,
   );

 }

 function customUser_install() {
   $schema = drupal_get_schema('users');
   db_add_field('users', 'detail', $schema['fields']['detail']);
 }

 function customUser_form_alter(&$form, &$form_state, $form_id) {
 // check to see if the form is the user registration or user profile form
 // if not then return and don’t do anything
   if (!($form_id == 'user_register_form' || $form_id == 'user_profile_form')) {
     return;
   }
   $form['account']['detail'] = array(
       '#type' => 'textfield',
       '#title' => t('Additional Detail'),
     );
   }

1 个答案:

答案 0 :(得分:1)

正确的答案需要更多细节。我只能假设你做了什么。

  1. 您在{users}表中添加了字段。您没有更新数据库架构,这使得drupal_write_record不知道新字段,这就是它们未被填充的原因。
  2. 您使用字段创建了一个新表{my_table}。
  3. 在这两种情况下,您都需要hook_user_insert()

    /**
     * Implements hook_user_insert().    
     */
    function mymodule_user_insert(&$edit, $account, $category) {
      // Here you add the code to update the entry in {users} table,
      // or int your custom table.
      // $edit has the values from the form, $account->uid has the
      // uid of the newly created user.
    }
    

    注意:如果我的第一个假设是正确的,那不是drupal方式。你应该完成第二种方式。即使在这种情况下,也可以使用hook_schema在mymodule.install中创建表,而不是使用db_add_field()。

    对于drupal 7,您可以使用配置文件模块(核心)或profile2来实现这一目标。

    基于该代码 尝试在alter。形式内更改为。

    $account = $form['#user'];
    $form['account']['detail'] = array(
      '#type' => 'textfield',
      '#title' => t('Additional Detail'),
      '#default_value' => $account->detail,
    );