User Profile Problem Topic is solved

For Joomla! 3.x Coding related discussions, you could also use: http://groups.google.com/group/joomla-dev-general

Moderators: ooffick, General Support Moderators

Forum rules
Locked
christoforosKor
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 112
Joined: Mon Aug 27, 2012 2:22 pm

User Profile Problem

Post by christoforosKor » Thu Jul 14, 2022 2:31 pm

Hello,

I am uising Joomla 3.9.22 and I am trying to create a user porfile.

I have on field which is stored correctly in the database. It is a drop down field with two options.

When I reload the user form again it does not shows me the the value stored in the database but the first option.
It seems that the form does not bind my values but I can not understand why.

My profile xml is

Code: Select all

<?xml version="1.0" encoding="utf-8"?>
	
<form>
	<fields name="mnsprofile">
		<fieldset name="mnsprofile"
			label="PLG_USER_MNSPROFILE_SLIDER_LABEL"
		>
			<field
				name="uniqueLoginState"
				type="List"
				description="PLG_USER_MNS_PROFILE_FIELD_UNIQUE_LOGIN_STATE_DESC"
				label="PLG_USER_MNS_PROFILE_FIELD_UNIQUE_LOGIN_STATE_LABEL"
			>
                            <option value="1">OPTION_UNIQUE_LOGIN</option>
                            <option value="2">OPTION_NO_UNIQUE_LOGIN</option>
                        
                        </field>


		</fieldset>
	</fields>
</form>
and my php file msnprofile.php is

Code: Select all

<?php
 /**
  * @version		
  * @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;
 
 use Joomla\CMS\Factory;
 use Joomla\CMS\Form\Form;

  /**
   * An example custom profile plugin.
   *
   * @package		Joomla.Plugins
   * @subpackage	user.profile
   * @version		1.6
   */
  class plgUserMnsprofile 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 \'mnsprofile.%\'' .
			' 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->mnsprofile = array();
		foreach ($results as $v) {
			$k = str_replace('mnsprofile.', '', $v[0]);
			$data->mnsprofile[$k] = json_decode($v[1], true);
		}

		return true;
	}

        
        
        /**
	 * 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)
	{
		// 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 (!isset($data->profile) && $userId > 0)
			{
				// Load the profile data from the database.
				$db = Factory::getDbo();
				$db->setQuery(
					'SELECT profile_key, profile_value FROM #__user_profiles'
						. ' WHERE user_id = ' . (int) $userId . " AND profile_key LIKE 'mnsprofile.%'"
						. ' ORDER BY ordering'
				);

				try
				{
					$results = $db->loadRowList();
				}
				catch (RuntimeException $e)
				{
					$this->_subject->setError($e->getMessage());

					return false;
				}

				// Merge the profile data.
				$data->profile = array();

				foreach ($results as $v)
				{
					$k = str_replace('mnsprofile.', '', $v[0]);
					$data->profile[$k] = json_decode($v[1], true);

					if ($data->profile[$k] === null)
					{
						$data->profile[$k] = $v[1];
					}
				}
			}

//			if (!HTMLHelper::isRegistered('users.url'))
//			{
//				HTMLHelper::register('users.url', array(__CLASS__, 'url'));
//			}
//
//			if (!HTMLHelper::isRegistered('users.calendar'))
//			{
//				HTMLHelper::register('users.calendar', array(__CLASS__, 'calendar'));
//			}
//
//			if (!HTMLHelper::isRegistered('users.tos'))
//			{
//				HTMLHelper::register('users.tos', array(__CLASS__, 'tos'));
//			}
//
//			if (!HTMLHelper::isRegistered('users.dob'))
//			{
//				HTMLHelper::register('users.dob', array(__CLASS__, 'dob'));
//			}
		}

		return true;
	}

        
	/**
	 * Adds additional fields to the user editing form
	 *
	 * @param   Form   $form  The form to be altered.
	 * @param   mixed  $data  The associated data for the form.
	 *
	 * @return  boolean
	 *
	 * @since   1.6
	 */
	public function onContentPrepareForm(Form $form, $data)
	{
		// Load user_profile plugin language
		$lang = JFactory::getLanguage();
		$lang->load('plg_user_mnsprofile', JPATH_ADMINISTRATOR);

		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;
		}

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

		$fields = array(
			'uniqueLoginState'
		);

		// Change fields description when displayed in frontend or backend profile editing
//		$app = Factory::getApplication();

//		if ($app->isClient('site') || $name === 'com_users.user' || $name === 'com_admin.profile')
//		{
//			$form->setFieldAttribute('address1', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('address2', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('city', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('region', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('country', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('postal_code', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('phone', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('website', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('favoritebook', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('aboutme', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('dob', 'description', 'PLG_USER_PROFILE_FILL_FIELD_DESC_SITE', 'profile');
//			$form->setFieldAttribute('tos', 'description', 'PLG_USER_PROFILE_FIELD_TOS_DESC_SITE', 'profile');
//		}

//		$tosArticle = $this->params->get('register_tos_article');
//		$tosEnabled = $this->params->get('register-require_tos', 0);

		// We need to be in the registration form and field needs to be enabled
//		if ($name !== 'com_users.registration' || !$tosEnabled)
//		{
//			// We only want the TOS in the registration form
//			$form->removeField('tos', 'profile');
//		}
//		else
//		{
//			// Push the TOS article ID into the TOS field.
//			$form->setFieldAttribute('tos', 'article', $tosArticle, 'profile');
//		}

		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)
				{
					$form->setFieldAttribute($field, 'required', ($this->params->get('profile-require_' . $field) == 2) ? 'required' : '', 'profile');
				}
				// Remove the field if it is disabled in registration and profile
				elseif ($this->params->get('register-require_' . $field, 1) == 0
					&& $this->params->get('profile-require_' . $field, 1) == 0)
				{
					$form->removeField($field, 'mnsprofile');
				}
			}
			// 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' : '', 'mnsprofile');
				}
				else
				{
					$form->removeField($field, 'mnsprofile');
				}
			}
			// 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' : '', 'mnsprofile');
				}
				else
				{
					$form->removeField($field, 'mnsprofile');
				}
			}
		}

		// Drop the profile form entirely if there aren't any fields to display.
		$remainingfields = $form->getGroup('mnsprofile');

		if (!count($remainingfields))
		{
			$form->removeGroup('mnsprofile');
		}

		return true;
	}

        
        

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

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

				$tuples = array();
				$order	= 1;
				foreach ($data['mnsprofile'] as $k => $v) {
					$tuples[] = '('.$userId.', '.$db->quote('mnsprofile.'.$k).', '.$db->quote(json_encode($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 'mnsprofile.%'"
				);

				if (!$db->query()) {
					throw new Exception($db->getErrorMsg());
				}
			}
			catch (JException $e)
			{
				$this->_subject->setError($e->getMessage());
				return false;
			}
		}

		return true;
	}


 }
Any help is appreciated

christoforosKor
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 112
Joined: Mon Aug 27, 2012 2:22 pm

Re: User Profile Problem

Post by christoforosKor » Tue Jul 19, 2022 3:04 pm

I found the solution.
For who ever might have the same problem, in the onContentPrepareData function I changed the following lines

Code: Select all

				$data->profile = array();

				foreach ($results as $v)
				{
					$k = str_replace('mnsprofile.', '', $v[0]);
					$data->profile[$k] = json_decode($v[1], true);

					if ($data->profile[$k] === null)
					{
						$data->profile[$k] = $v[1];
					}
				}
				

with

Code: Select all


				$data->mnsprofile = array();

				foreach ($results as $v)
				{
					$k = str_replace('mnsprofile.', '', $v[0]);
					$data->mnsprofile[$k] = json_decode($v[1], true);

					if ($data->mnsprofile[$k] === null)
					{
						$data->mnsprofile[$k] = $v[1];
					}
				}


Locked

Return to “Joomla! 3.x Coding”