代码之家  ›  专栏  ›  技术社区  ›  Manoj Sreekumar

Drupal自定义用户注册表单

  •  0
  • Manoj Sreekumar  · 技术社区  · 12 年前

    我已经使用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 回复  |  直到 12 年前
        1
  •  1
  •   tic2000    12 年前

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

    1. 您向{users}表中添加了字段。您没有更新数据库模式,这使得drupal_write_record不知道新字段,这就是它们未填充的原因。
    2. 您使用字段创建了一个新表{my_table}。

    在这两种情况下,您都需要 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,
    );
    
    推荐文章