Thursday, May 17, 2012

Creating a Profile Plugin for Joomla 1.6

So there is other documentation out there. I'm basing most of this article on the official Joomla 1.6 documentation: http://docs.joomla.org/Creating_a_profile_plugin and I want to use an example that worked for me. Important: This is for Joomla version 1.6.x+.

Aim / Objective
  1. Add a field with a dropdown list.
  2. Add a button to upload an avatar (and sync with 3rd party avatar).
Not riveting stuff but something that all my clients want. Fortunately for me, I just created one plugin which I can install on any number of Joomla 1.6 sites and it does all this for me... Neat huh?

Folder
I'm going to shove all these files into a folder which I will then compress and install using the Joomla! CMS Extension Manager.

I'm going to call the folder "profile5" (without the double-quotes) and create a subfolder called "profiles".

So I should end up with the following file/directory structure:
     ./profile5
     ./profile5/profiles
Also copy one of those handy blank "index.html" files into each of these folders in case "directory listing" gets enabled on your server.I'm going to refer to the files to create as being in this folder.

./profile5/profile5.php
<?php
 /**
  * @version
  * @copyright  Copyright (C) 2011 JoelLipman.Com, 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','com_users.user','com_admin.profile'))){
                        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 .
                        ' AND profile_key LIKE \'profile5.%\'' .
                        ' 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->profile5 = array();
                foreach ($results as $v) {
                        $k = str_replace('profile5.', '', $v[0]);
                        $data->profile5[$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_profile5', 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','com_admin.profile'))) {
                        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 allergytime field is required.
                        if ($this->params->get('profile-require_allergytime', 1) > 0) {
                                $form->setFieldAttribute('allergytime', 'required', $this->params->get('profile-require_allergytime') == 2, 'profile');
                        } else {
                                $form->removeField('allergytime', '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 allergytime field is required.
                        if ($this->params->get('register-require_allergytime', 1) > 0) {
                                $form->setFieldAttribute('allergytime', 'required', $this->params->get('register-require_allergytime') == 2, 'profile');
                        } else {
                                $form->removeField('allergytime', 'profile');
                        }
                }
        }

        function onUserAfterSave($data, $isNew, $result, $error)
        {
                $userId        = JArrayHelper::getValue($data, 'id', 0, 'int');
                if ($userId && $result && isset($data['profile5']) && (count($data['profile5'])))
                {
                        try
                        {
                                $db = &JFactory::getDbo();
                                $db->setQuery('DELETE FROM #__user_profiles WHERE user_id = '.$userId.' AND profile_key LIKE \'profile5.%\'');
                                if (!$db->query()) {
                                        throw new Exception($db->getErrorMsg());
                                }
                                $tuples = array();
                                $order = 1;
                                foreach ($data['profile5'] as $k => $v) {
                                        $tuples[] = '('.$userId.', '.$db->quote('profile5.'.$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;
        }

        /**
         * Remove all user profile information for the given user ID
         *
         * Method is called after user data is deleted from the database
         *
         * @param       array           $user           Holds the user data
         * @param       boolean         $success        True if user was succesfully stored in the database
         * @param       string          $msg            Message
         */
        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 #__user_profiles WHERE user_id = '.$userId .
                                        " AND profile_key LIKE 'profile5.%'"
                                );

                                if (!$db->query()) {
                                        throw new Exception($db->getErrorMsg());
                                }
                        }
                        catch (JException $e)
                        {
                                $this->_subject->setError($e->getMessage());
                                return false;
                        }
                }
                return true;
        }
 }
 ?>
./profile5/profile5.xml
<?xml version="1.0" encoding="utf-8"?>
        <!-- $Id:  -->
 <extension version="1.6" type="plugin" group="user">
        <name>User - Profile - JoelLipman.Com</name>
        <author>Joel Lipman</author>
        <creationDate>April 2011</creationDate>
        <copyright>(C) 2011 JoelLipman.Com. All rights reserved.</copyright>
        <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
        <authorEmail>
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it
 </authorEmail>
        <authorUrl>www.joellipman.com</authorUrl>
        <version>1.6.0</version>
        <description>PLG_USER_PROFILE5_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_profile5.ini</language>
                <language tag="en-GB">en-GB.plg_user_profile5.sys.ini</language>
        </languages>

        <config>
                <fields name="params">

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

                                <field name="register-require_allergytime" type="list"
                                        description="PLG_USER_PROFILE5_FIELD_ALLERGYTIME_DESC"
                                        label="PLG_USER_PROFILE5_FIELD_ALLERGYTIME_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_PROFILE5_FIELD_NAME_PROFILE_REQUIRE_USER"
                                />

                                <field name="profile-require_allergytime" type="list"
                                        description="PLG_USER_PROFILE5_FIELD_ALLERGYTIME_DESC"
                                        label="PLG_USER_PROFILE5_FIELD_ALLERGYTIME_LABEL"
                                >
                                        <option value="2">JOPTION_REQUIRED</option>
                                        <option value="1">JOPTION_OPTIONAL</option>
                                        <option value="0">JDISABLED</option>
                                </field>

                        </fieldset>

                </fields>
        </config>
 </extension>

./profile5/en-GB.plg_user_profile5.ini
; Joomla! Project
; Copyright (C) 2011 JoelLipman.com. All rights reserved.
; License http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php
; Note : All ini files need to be saved as UTF-8

PLG_USER_PROFILE5_XML_DESCRIPTION="User Profile Plug-in by JoelLipman.Com to add extra fields to the user forms."
PLG_USER_PROFILE5="User - Profile - JoelLipman.Com"
PLG_USER_PROFILE5_SLIDER_LABEL="User Profile - JoelLipman.Com"
PLG_USER_PROFILE5_FIELD_NAME_REGISTER_REQUIRE_USER="User profile fields for registration and administrator user profile - JoelLipman.Com forms"
PLG_USER_PROFILE5_FIELD_NAME_PROFILE_REQUIRE_USER="User profile fields for profile - JoelLipman.Com edit form"
PLG_USER_PROFILE5_FIELD_ALLERGYTIME_DESC="How long have you been dealing with this allergy?"
PLG_USER_PROFILE5_FIELD_ALLERGYTIME_LABEL="Time With Allergy?"
PLG_USER_PROFILE_FIELD_ALLERGYTIME_MESSAGE="Select one of the options"
PLG_USER_PROFILE5_XML_DESCRIPTION="User Profile - JoelLipman.Com Plugin"
JOELLIPMAN_BOOLEANYES="Yes"
JOELLIPMAN_BOOLEANNO="No"
JOELLIPMAN_ALLERGYTIMEOPTION0="Less than 6 months"
JOELLIPMAN_ALLERGYTIMEOPTION1="Less than a year"
JOELLIPMAN_ALLERGYTIMEOPTION2="1 year"
JOELLIPMAN_ALLERGYTIMEOPTION3="5 years"
JOELLIPMAN_ALLERGYTIMEOPTION4="10 years+"
PLG_USER_PROFILE5_FIELD_ALLERGYTIMEDISP_DESC="Choose to hide from other users?"
PLG_USER_PROFILE5_FIELD_ALLERGYTIMEDISP_LABEL="Hide from others?"

./profile5/en-GB.plg_user_profile5.sys.ini
; Joomla! Project
; Copyright (C) 2011 JoelLipman.com. All rights reserved.
; License http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php
; Note : All ini files need to be saved as UTF-8

PLG_USER_PROFILE5="User - Profile - JoelLipman.com"
PLG_USER_PROFILE5_XML_DESCRIPTION="User Profile Plug-in - JoelLipman.Com"

./profile5/profiles/profile.xml
<?xml version="1.0" encoding="utf-8"?>
	<!-- $Id: profile.xml 20156 2011-04-27 13:10:16Z joellipman $ -->
<form>
	<fields name="profile">
		<fieldset name="profile">
			<field
				name="allergytime"
				type="list"
				id="allergytime"
				description="PLG_USER_PROFILE5_FIELD_ALLERGYTIME_DESC"
				filter="string"
				label="PLG_USER_PROFILE5_FIELD_ALLERGYTIME_LABEL"
				message="PLG_USER_PROFILE_FIELD_ALLERGYTIME_MESSAGE"
				>
					<option value="0">JOELLIPMAN_ALLERGYTIMEOPTION0</option>
					<option value="1">JOELLIPMAN_ALLERGYTIMEOPTION1</option>
					<option value="2">JOELLIPMAN_ALLERGYTIMEOPTION2</option>
					<option value="3">JOELLIPMAN_ALLERGYTIMEOPTION3</option>
					<option value="4">JOELLIPMAN_ALLERGYTIMEOPTION4</option>
				</field>
			<field name="allergytimedisplay" type="list"
					description="PLG_USER_PROFILE5_FIELD_ALLERGYTIMEDISP_DESC"
					label="PLG_USER_PROFILE5_FIELD_ALLERGYTIMEDISP_LABEL"
				>
					<option value="1">JOELLIPMAN_BOOLEANYES</option>
					<option value="0">JOELLIPMAN_BOOLEANNO</option>
				</field>

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

Add comment

Please note: all comments are reviewed before being published.


Security code
Refresh

Member Login

Joes Latest Members

A huge WELCOME goes to today's newest members:

  • infonat
Member Signups (Activated)
BeforeCurrentTrend
Day21=
Week105ê
Month11224ê
Year2,265612ê

Member Stats
58 guests are currently online.
1,178 members are still deciding.
There are 5,935 members in total.

Latest Comments

Paypal Donations

Want to support my work? Any donation is a blessing :c)