简体   繁体   English

自定义Joomla配置文件插件注册用户数据库表更新问题

[英]Custom Joomla profile plugin registered user database table update issues

I have a custom extension that uses the Joomla profile plugin and extends it to provide additional fields to the user profile in the administrator panel and in the registered area on the front end of the website. 我有一个自定义扩展,它使用Joomla配置文件插件并对其进行扩展,以便在管理员面板和网站前端的注册区域中为用户配置文件提供其他字段。 The fields are set to display to admins-only, be disabled, be optional or be required. 这些字段设置为仅显示管理员,禁用,可选或需要。 When they are set to admin-only, they do not show on the front end of the website in the "edit your profile" form. 当它们设置为仅限管理员时,它们不会在“编辑您的个人资料”表单中显示在网站的前端。 The plugin handles the UPDATE command for all fields with no issues in the administrator panel, but when the UPDATE command is triggered by a user updating their profile on the front end, all of the admin-only fields are overwritten with empty values. 插件处理所有字段的UPDATE命令,管理员面板中没有任何问题,但是当用户在前端更新其配置文件触发UPDATE命令时,所有仅管理员字段都将被空值覆盖。 All of the other fields, whether they are optional or required are successfully saved or maintained in the form. 所有其他字段,无论是可选的还是必需的,都可以在表单中成功保存或维护。 I have included the custom profile plugin's PHP code below. 我在下面包含了自定义配置文件插件的PHP代码。

<?php
/**
* @package     Joomla.Plugin
* @subpackage  User.profile
*
* @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license     GNU General Public License version 2 or later; see LICENSE.txt
*/

defined('JPATH_BASE') or die;

/**
* An example custom profile plugin.
*
* @since  1.6
*/
class PlgUserKiduka extends JPlugin
{

/**
 * Load the language file on instantiation.
 *
 * @var    boolean
 * @since  3.1
 */
protected $autoloadLanguage = true;

/**
 * Constructor
 *
 * @param   object  &$subject  The object to observe
 * @param   array   $config    An array that holds the plugin configuration
 *
 * @since   1.5
 */
public function __construct(& $subject, $config)
{
    parent::__construct($subject, $config);
    JFormHelper::addFieldPath(__DIR__ . '/fields');
}

/**
 * Runs on content preparation
 *
 * @param   string  $context  The context for the data
 * @param   object  $data     An object containing the data for the form.
 *
 * @return  boolean
 *
 * @since   1.6
 */
public function onContentPrepareData($context, $data)
{
    // No need to display the context variable as a heading on the registration page
    // echo '<h1>'.$context.'</h1>';
    // Check we are manipulating a valid form.
    if (!in_array($context, array('com_users.profile', 'com_users.user', 'com_users.registration', 'com_admin.profile')))
    {
        return true;
    }

    if (is_object($data))
    {
        $userId = isset($data->id) ? $data->id : 0;

        if ($userId > 0)
        {
            // Load the profile data from the database.
            $db = JFactory::getDbo();
            $db->setQuery(
                'SELECT * FROM #__kiduka_accounts WHERE user_id = ' . $userId
            );
            $data->kiduka = $db->loadObject();
        }
    }

    return true;
}


/**
 * adds additional fields to the user editing form
 *
 * @param   JForm  $form  The form to be altered.
 * @param   mixed  $data  The associated data for the form.
 *
 * @return  boolean
 *
 * @since   1.6
 */
public function onContentPrepareForm($form, $data)
{

    if (!($form instanceof JForm))
    {
        $this->_subject->setError('JERROR_NOT_A_FORM');

        return false;
    }

    // Check we are manipulating a valid form.
    $name = $form->getName();

    if (!in_array($name, array('com_admin.profile', 'com_users.user', 'com_users.profile', 'com_users.registration')))
    {
        return true;
    }

    foreach(JFactory::getUser()->get('groups') as $group){
        if(in_array($group, $this->params->get('usergroup'))){
            return true;
        }
    }

    // Add the registration fields to the form.
    JForm::addFormPath(__DIR__ . '/profiles');
    $form->loadFile('profile', false);

    $fields = array(
        'firechief',
        'title',
        'membership_no',
        'organization',
        'organizationtype',
        'membertype',
        'afcaregion',
        'municipalcode',
        'membershipyear',
        'address1',
        'address2',
        'city',
        'province',
        'postalcode',
        'country',
        'businessphone',
        'homephone',
        'cellphone',
        'fax',
        'notes',
        'gstexempt',
        'billorganization',
        'billaddress1',
        'billaddress2',
        'billcity',
        'billprovince',
        'billpostalcode',
        'billcountry'
    );

    // Change fields description when displayed in front-end or back-end profile editing
    $app = JFactory::getApplication();

    foreach ($fields as $field)
    {
        // Case using the users manager in admin
        if ($name == 'com_users.user')
        {
            // Toggle whether the field is required.
            if ($this->params->get('profile-require_' . $field, 1) > 0 || $this->params->get('profile-require_' . $field, 1) == -1)
            {
                $form->setFieldAttribute($field, 'required', ($this->params->get('profile-require_' . $field) == 2) ? 'required' : '', 'kiduka');
            }
            else
            {
                $form->removeField($field, 'kiduka');
            }
        }
        // Case registration
        elseif ($name == 'com_users.registration')
        {
            // Toggle whether the field is required.
            if ($this->params->get('register-require_' . $field, 1) > 0)
            {
                $form->setFieldAttribute($field, 'required', ($this->params->get('register-require_' . $field) == 2) ? 'required' : '', 'kiduka');
            }
            else
            {
                $form->removeField($field, 'kiduka');
            }
        }
        // Case profile in site or admin
        elseif ($name == 'com_users.profile' || $name == 'com_admin.profile')
        {
            // Toggle whether the field is required.
            if ($this->params->get('profile-require_' . $field, 1) > 0)
            {
                $form->setFieldAttribute($field, 'required', ($this->params->get('profile-require_' . $field) == 2) ? 'required' : '', 'kiduka');
            }
            else
            {
                $form->removeField($field, 'kiduka');
            }
        }
    }

    return true;
}

/**
 * saves user profile data
 *
 * @param   array    $data    entered user data
 * @param   boolean  $isNew   true if this is a new user
 * @param   boolean  $result  true if saving the user worked
 * @param   string   $error   error message
 *
 * @return bool
 */
public function onUserAfterSave($data, $isNew, $result, $error)
{
    $user = JFactory::getUser();
    $modified_by = $user->get('id');
    $userId = JArrayHelper::getValue($data, 'id', 0, 'int');

    $datenow = JFactory::getDate();
    $modified = $datenow->toSql();

    $fields = array(
                // 'membership_no',
                'title',
                'firechief',
                'organization',
                'address1',
                'address2',
                'city',
                'province',
                'postalcode',
                'country',
                'businessphone',
                'homephone',
                'cellphone',
                'fax',
                'organizationtype',
                'membertype',
                'billorganization',
                'billaddress1',
                'billaddress2',
                'billcity',
                'billprovince',
                'billpostalcode',
                'billcountry',
                'afcaregion',
                'gstexempt',
                'notes',
                'municipalcode',
                'membershipyear'
            );

    if($isNew){
        $query = 'INSERT INTO #__kiduka_accounts VALUES(NULL, '.$userId.', "", '.$userId.', '.$userId;
        foreach($fields as $field){
            $query .= ', "'.$data['kiduka'][$field].'"';
        }
        $query .= ')';
    }else{
        $query  = 'UPDATE #__kiduka_accounts SET ';
        $query .= 'modified = "'.$modified.'", ';
        $query .= 'modified_by = "'.$modified_by.'", ';
        $query .= 'membership_no = "'.$userId.'", ';
        for($i = 0; $i < count($fields); $i++){
            $query .= $fields[$i] . ' = "'.$data['kiduka'][$fields[$i]].'"';
            if($i < count($fields) - 1){
                $query .= ', ';
            }

        }
        $query .= ' WHERE user_id = "'.$userId.'"';
    }

    // var_dump($data);
    // die();

    $db = JFactory::getDbo();
    $db->setQuery($query);
    $db->query();

    // var_dump($query);
    // die();

    return true;
}

public function onUserAfterDelete($user, $success, $msg)
{
    if (!$success)
    {
        return false;
    }

    $userId = JArrayHelper::getValue($user, 'id', 0, 'int');

    if ($userId)
    {
        try
        {
            $db = JFactory::getDbo();
            $db->setQuery(
                'DELETE FROM #__kiduka_accounts WHERE user_id = ' . $userId);

            $db->execute();
        }
        catch (Exception $e)
        {
            $this->_subject->setError($e->getMessage());

            return false;
        }
    }

    return true;
    }
}

@Elin I have figured it out. @Elin我已经弄清楚了。 It was suggested on the Joomla forum to use two $fields arrays, one for the front-end profile form and another with all of the fields for the administrator user manager profile form. 在Joomla论坛上建议使用两个$ fields数组,一个用于前端配置文件表单,另一个用于管理员用户管理器配置文件表单的所有字段。 I have included the PHP code for the onUserAfterSave function below. 我在下面列出了onUserAfterSave函数的PHP代码。 The if($app->isSite()) if/else shows the limited fields on the front-end profile form and the full list of fields on the administrator profile form. if($ app-> isSite()) if / else显示前端配置文件表单上的有限字段和管理员配置文件表单上的完整字段列表。

public function onUserAfterSave($data, $isNew, $result, $error)
{
    $app = JFactory::getApplication();
    $user = JFactory::getUser();
    $modified_by = $user->get('id');
    $userId = JArrayHelper::getValue($data, 'id', 0, 'int');

    $datenow = JFactory::getDate();
    $modified = $datenow->toSql();

    if($app->isSite())
    {
        $fields = array(
            'address1',
            'address2',
            'city',
            'province',
            'postalcode',
            'country',
            'businessphone',
            'homephone',
            'cellphone',
            'fax'
        );  
    }
    else
    {
        $fields = array(
            'firechief',
            'title',
            'organization',
            'organizationtype',
            'membertype',
            'afcaregion',
            'municipalcode',
            'membershipyear',
            'address1',
            'address2',
            'city',
            'province',
            'postalcode',
            'country',
            'businessphone',
            'homephone',
            'cellphone',
            'fax',
            'notes',
            'gstexempt',
            'billorganization',
            'billaddress1',
            'billaddress2',
            'billcity',
            'billprovince',
            'billpostalcode',
            'billcountry'
        );
    }

    if($isNew)
    {
        $db = JFactory::getDbo();
        $query = 'INSERT INTO #__kiduka_accounts VALUES(NULL, '.$userId.', "", '.$userId.', '.$userId;
        foreach($fields as $field)
        {
            $query .= ', "'.$data['kiduka'][$field].'"';
        }
        $query .= ')';
    }
    else
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query .= 'UPDATE #__kiduka_accounts SET ';
        $query .= 'modified = "'.$modified.'", ';
        $query .= 'modified_by = "'.$modified_by.'", ';
        $query .= 'membership_no = "'.$userId.'", ';
        for($i = 0; $i < count($fields); $i++)
        {
            $query .= $fields[$i] . ' = "'.$data['kiduka'][$fields[$i]].'"';
            if($i < count($fields) - 1)
            {
                $query .= ', ';
            }

        }
        $query .= ' WHERE user_id = "'.$userId.'"';
    }

    $db->setQuery($query);
    $db->execute();

    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM