上一节介绍了创建一个自定义注册表单字段的插件的理论。这一篇,主要给出具体的实现代码。

自定义的注册表单(customfields\customform.xml)


<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="customfields">
		<fieldset name="customfields" label="PLG_CUSTOMFIELDS_FIELDSET_LABEL" description="PLG_CUSTOMFIELDS_FIELDSET_DESC" >
			<field
				name="phone"
				type="text"
				id="phone"
				description="PLG_CUSTOMFIELDS_PHONE_DESC"
				label="PLG_CUSTOMFIELDS_PHONE_LABEL"
			/>
		</fieldset>
	</fields>
</form>

插件核心文件( customfields.php)


<?php
/**
 * @zmax customfields plugin
 */
class plgUserCustomfields extends JPlugin
{
	/**
	 *	constructor
	 *
	 * @access	 protected
	 * @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);
		//jimport('joomla.log.log');
		//JLog::addLogger(array('text_file'=>'plg_customfield.log.php','text_file_path'=>JPATH_PLUGINS.DS.'user'.DS.'customfields') ,JLOG::ALL ,array('zmax' ,'jerror'));
		$this->loadLanguage();
	 }
	
    /**
     * @param  string The context of the data
	 * @param 	int    The user id
	 * @param 	object 	
	 * @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.registration','com_users.user','com_admin.profile')))
		{
			return true;
		}
		//可以从$data中获得用户id的信息
		$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 \'customfields.%\''.
				' 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
		//php是可以为对象零时增加一个属性的
		$data->customfields = array();
		foreach($results as $v)
		{
			$k = str_replace('customfields.','',$v[0]);//去掉前缀
			$data->customfields[$k] = json_decode($v[1] ,true);//键和值对应 其中用到了json_decode
		}
		
		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)
	 {
		//JLog::add("trigger onContentPrepareForm " ,JLOG::INFO ,'zmax');
		
		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__).'/customform');
		
		// Load our custom form
		$form->loadFile('myform' ,false);
		
		// Toggle whether the somthing field is required]

		if($this->params->get('enable-phone' ,1) > 0)
		{
			//需要研究一下setFieldAttribute这个方法的参数详解
			//setFieldAttribute 具有4个参数
			// $field 字段的名称
			// $attribute 属性的名称
			// $value 属性的值
			// $group 组的名称
			$form->setFieldAttribute('phone' ,'required' ,$this->params->get('enable-phone') == 2 ,'myform');
		}else
		{
			$form->removeField('phone','myform');
		}
		
	 }
	 
	 
	 function onUserAfterSave($data ,$isNew ,$result ,$error)
	 {
		//学习一些JArrayHelper::getValue这个函数的作用
		$userId = JArrayHelper::getValue($data ,'id' ,0 ,'int');
	
		if($userId && $result && isset($data['customfields']) && (count($data['customfields'])))
		{
			try{
					$db = JFactory::getDbo();
					$db->setQuery('DELETE FROM #__user_profiles WHERE user_id = '.$userId .' AND profile_key LIKE \'customfields.%\'');
					if(!$db->query())
					{
						throw new Exception($db->getErrorMsg());
					}
					
					$tuples = array();
					$order = 1;
					foreach($data['customfields'] as $k => $v)
					{
						$tuples[]='('.$userId.', '.$db->quote('customfields.'.$k).', '.$db->quote(json_encode($v)).', '.$order++.')';
					}
					
					$db->setQuery('INSERT INTO #__user_profiles VALUE '.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 Ture if user was succesfully stored in the databse
	  * @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 'customfields.%'");
					if(!($db->query()))
					{
						throw new Exception($db->getErrorMsg());
					}
				}catch(JException $e)
				{
					$this->_subject->setError($e->getMesage());
					return false;
				}
			}
			return true;
	  }
}
?>

其他


 需要下载该扩展的完整安装包,请前往本站的下载区进行下载。

评论

  • 未找到评论