@DavidFritsch的回答非常有帮助。我发现的几个问题是:
A)您不能完全删除某些必填字段,因为它会导致表单提交时的数据过滤出现问题(请参见下面的代码中的注释)。要解决此问题,请隐藏而不是从表单对象中删除字段。B)只有在为时已晚以防止注册验证逻辑拒绝表单提交时才触发onUserBeforeSave事件。而是使用onUserBeforeDataValidation事件。
在我的特定情况下,我想要的只是电子邮件地址和密码。但是,Joomla带来了一个麻烦,因为电子邮件地址是在密码之后显示的(由registration.xml文件中声明的字段顺序决定),从用户体验的角度来看,这似乎很愚蠢。要解决此问题,我将用户名字段重新标记为“电子邮件地址”,而是隐藏了电子邮件地址字段。然后,在表单提交时默认使用用户名发送电子邮件。
(要注意的一点:与David的回答也考虑其他形式相比,出于我的目的,我已将该插件限制为只能在“ com_users.registration”表单上运行。)
class PlgUserSimpleRegistration extends JPlugin
{
function onContentPrepareForm($form, $data)
{
if (!($form instanceof JForm))
{
$this->_subject->setError('JERROR_NOT_A_FORM');
return false;
}
// Check we are manipulating the registration form
if ($form->getName() != 'com_users.registration')
{
return true;
}
// Check whether this is frontend or admin
if (JFactory::getApplication()->isAdmin()) {
return true;
}
// Remove/Hide fields on frontend
// Note: since the onContentPrepareForm event gets fired also on
// submission of the registration form, we need to hide rather than
// remove the mandatory fields. Otherwise, subsequent filtering of the data
// from within JModelForm.validate() will result in the required fields
// being stripped from the user data prior to attempting to save the user model,
// which will trip an error from inside the user object itself on save!
$form->removeField('password2');
$form->removeField('email2');
$form->setFieldAttribute('name', 'type', 'hidden');
$form->setValue('name', null, 'placeholder');
$form->setFieldAttribute('email1', 'type', 'hidden');
$form->setValue('email1', null, JUserHelper::genRandomPassword(10) . '@invalid.nowhere');
// Re-label the username field to 'Email Address' (the Email field
// ordinarily appears below the password field on the default Joomla
// registration form)
$form->setFieldAttribute('username', 'label', 'COM_USERS_REGISTER_EMAIL1_LABEL');
return true;
}
function onUserBeforeDataValidation($form, &$user) {
if ($form->getName() != 'com_users.registration') {
return true;
}
if (!$user['username']) {
// Keep up the pretense from above!
$form->setFieldAttribute('username', 'label', 'COM_USERS_REGISTER_EMAIL1_LABEL');
return true;
}
if (!$user['name'] or $user['name'] === 'placeholder') {
$user['name'] = $user['username'];
$user['email1'] = $user['email2'] = $user['username'];
$user['password2'] = $user['password1'];
}
}
}