Actions

Creating a profile plugin

From Joomla! Documentation

Revision as of 10:57, 16 June 2010 by Elin (Talk | contribs)

Profile plugin is a new extension in Joomla! 1.6. It allows the addition of supplemental fields in the registration and profile forms of the com_user front end and in the user create/edit form in the back end.

A simple example plugin is included in the basic Joomla! installation as a proof of concept. Much more complex plugins are possible.

The example plugin takes advantage of on the onContentPrepareForm and onUserAfterSave events.

Multiple profile plugins may be included and will be rendered in sequence.

This page shows an example of a second plugin, named profile5. It adds a single field called something.

This is the file structure

plugin5.php
plugin5.xml
/profiles/profile.xml

The supplemental fields are created with xml file in the profiles folder.

<?xml version="1.0" encoding="utf-8"?>
        <!-- $Id: profile.xml 16723 2010-05-04 01:37:00Z eddieajau $ -->
<form>
        <fields name="profile">
                <fieldset name="profile"
                        label="PLG_USER_PROFILE_SLIDER_LABEL"
                >
                        <field
                                name="something"
                                type="text"
                                id="address1"
                                description="PLG_USER_PROFILE_FIELD_SOMETHING_DESC"
                                filter="string"
                                label="PLG_USER_PROFILE_FIELD_SOMETHING_LABEL"
                                message="PLG_USER_PROFILE_FIELD_SOMETHING_MESSAGE"
                                size="30"
                        />


                </fieldset>
        </fields>
</form>


profile5.php

 <?php
 /**
  * @version            $Id: profile.php 17685 2010-06-14 21:46:46Z dextercowley $
  * @copyright  Copyright (C) 2005 - 2010 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.
   *
   * @package           Joomla.Plugins
   * @subpackage        user.profile
   * @version           1.6
   */
  class plgUserProfile5 extends JPlugin
  {
        /**
         * @param       string  The context for the data
         * @param       int             The user id
         * @param       object
         * @return      boolean
         * @since       1.6
         */
        function onContentPrepareData($context, $data)
        {
                // Check we are manipulating a valid form.
                if (!in_array($context, array('com_users.profile', 'com_users.registration'))) {
                        return true;
                }

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

                // Load the profile data from the database.
                $db = &JFactory::getDbo();
                $db->setQuery(
                        'SELECT profile_key, profile_value FROM #__user_profiles' .
                        ' WHERE user_id = '.(int) $userId .
                        ' ORDER BY ordering'
                );
                $results = $db->loadRowList();

                // Check for a database error.
                if ($db->getErrorNum()) {
                        $this->_subject->setError($db->getErrorMsg());
                        return false;
                }

                // Merge the profile data.
                $data->profile = array();
                foreach ($results as $v) {
                        $k = str_replace('profile.', '', $v[0]);
                        $data->profile[$k] = $v[1];
                }

                return true;
        }

        /**
         * @param       JForm   The form to be altered.
         * @param       array   The associated data for the form.
         * @return      boolean
         * @since       1.6
         */
        function onContentPrepareForm($form, $data)
        {
                // Load user_profile plugin language
                $lang = JFactory::getLanguage();
                $lang->load('plg_user_profile', JPATH_ADMINISTRATOR);

                if (!($form instanceof JForm)) {
                        $this->_subject->setError('JERROR_NOT_A_FORM');
                        return false;
                }
                // Check we are manipulating a valid form.
                if (!in_array($form->getName(), array('com_users.profile', 'com_users.registration','com_users.user'))) {
                        return true;
                }
                if ($form->getName()=='com_users.profile')
                {
                        // Add the profile fields to the form.
                        JForm::addFormPath(dirname(__FILE__).'/profiles');
                        $form->loadFile('profile', false);
        
                        // Toggle whether the something field is required.
                        if ($this->params->get('profile-require_something', 1) > 0) {
                                $form->setFieldAttribute('something', 'required', $this->params->get('profile-require_something') == 2, 'profile');
                        } else {
                                $form->removeField('something', 'profile');
                        }
        
                //In this example, we treat the frontend registration and the back end user create or edit as the same. 
                elseif ($form->getName()=='com_users.registration' || $form->getName()=='com_users.user' )
                {               
                        // Add the registration fields to the form.
                        JForm::addFormPath(dirname(__FILE__).'/profiles');
                        $form->loadFile('profile', false);
                        
                        // Toggle whether the something field is required.
                        if ($this->params->get('register-require_something', 1) > 0) {
                                $form->setFieldAttribute('something', 'required', $this->params->get('register-require_something') == 2, 'profile');
                        } else {
                                $form->removeField('something', 'profile');
                        }
                }                       
        }

        function onUserAfterSave($data, $isNew, $result, $error)
        {
                $userId = JArrayHelper::getValue($data, 'id', 0, 'int');

                if ($userId && $result && isset($data['profile']) && (count($data['profile'])))
                {
                        try
                        {
                                $db = &JFactory::getDbo();
                                $db->setQuery('DELETE FROM #__user_profiles WHERE user_id = '.$userId);
                                if (!$db->query()) {
                                        throw new Exception($db->getErrorMsg());
                                }

                                $tuples = array();
                                $order  = 1;
                                foreach ($data['profile'] as $k => $v) {
                                        $tuples[] = '('.$userId.', '.$db->quote('profile.'.$k).', '.$db->quote($v).', '.$order++.')';
                                }

                                $db->setQuery('INSERT INTO #__user_profiles VALUES '.implode(', ', $tuples));
                                if (!$db->query()) {
                                        throw new Exception($db->getErrorMsg());
                                }
                        }
                        catch (JException $e) {
                                $this->_subject->setError($e->getMessage());
                                return false;
                        }
                }

                return true;
        }
 }


Profile5.xml controls whether the field is required, disabled or optional in the forms. Since profile5.php says to treat backend create/edit the same as registration only two sets of options are required, register and profile.

 <?xml version="1.0" encoding="utf-8"?>
        <!-- $Id:  -->
 <install version="1.6" type="plugin" group="user">
        <name>plg_user_profile5</name>
        <author>Joomla! Project</author>
        <creationDate>January 2008</creationDate>
        <copyright>(C) 2005 - 2010 Open Source Matters. All rights reserved.</copyright>
        <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
        <authorEmail>admin@joomla.org</authorEmail>
        <authorUrl>www.joomla.org</authorUrl>
        <version>1.6.0</version>
        <description>PLG_USER_PROFILE_XML_DESCRIPTION</description>

        <files>
                <filename plugin="profile5">profile5.php</filename>
                <filename>index.html</filename>
                <folder>profiles</folder>
        </files>

        <languages>
                <language tag="en-GB">en-GB.plg_user_profile.ini</language>
                <language tag="en-GB">en-GB.plg_user_profile.sys.ini</language>
        </languages>

        <config>
                <fields name="params">

                        <fieldset name="basic">
                                <field name="register-require-user" type="spacer"
                                        label="PLG_USER_PROFILE_FIELD_NAME_REGISTER_REQUIRE_USER"
                                />

                                <field name="register-something" type="list"
                                        default="0"
                                        description="PLG_USER_PROFILE_FIELD_SOMETHING_DESC"
                                        label="PLG_USER_PROFILE_FIELD_ADDRESS1_LABEL"
                                >
                                        <option value="2">JOPTION_REQUIRED</option>
                                        <option value="1">JOPTION_OPTIONAL</option>
                                        <option value="0">JDISABLED</option>
                                </field>

                                <field name="profile-require-user" type="spacer"
                                        label="PLG_USER_PROFILE_FIELD_NAME_PROFILE_REQUIRE_USER"
                                />

                                <field name="profile-require_something" type="list"
                                        default="1"
                                        description="PLG_USER_PROFILE_FIELD_SOMETHING_DESC"
                                        label="PLG_USER_PROFILE_FIELD_SOMETHING_LABEL"
                                >
                                        <option value="2">JOPTION_REQUIRED</option>
                                        <option value="1">JOPTION_OPTIONAL</option>
                                        <option value="0">JDISABLED</option>
                                </field>

                        </fieldset>

                </fields>
        </config>
 </install>
 

By installing profile5 you can add new fields in addition to the ones in profile. You can also control which view levels see those fields. Alternatively, you can write a more complex common plugin with varying controls for different groups.