Документация для разработчиков
Темная тема

Мастер создания нового пользователя

Данный пример демонстрирует следующие аспекты программирования мастеров:

  • Обработку входных даннных;
  • Обработку ошибок шага;
  • Javascript-проверку входных данных;
  • Работу с элементами Web-форм;
  • Работу с переменными мастера.
<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
class MainUserFields extends CWizardStep
{
	function InitStep()
	{
		//ID шага
		$this->SetStepID("main_fields");
		//Заголовок
		$this->SetTitle("Основные поля пользователя");
		$this->SetSubTitle("Введите логин, пароль и e-mail нового пользователя");
		//Навигация
		$this->SetNextStep("additional_fields");
		$this->SetCancelStep("cancel");
		$wizard =& $this->GetWizard(); // Получаем ссылку на объект мастера
		$wizard->SetDefaultVar("active", "Y"); //Устанавливаем значение по умолчанию
	}
	function OnPostForm()
	{
		$wizard =& $this->GetWizard();
		if ($wizard->IsCancelButtonClick())
			return;
		$login = $wizard->GetVar("login");
		if (strlen($login) < 3)
			$this->SetError("Логин должен быть больше 3 символов", "login");
		else
		{
			$obUser = CUser::GetList($by="id", $order="desc", Array("LOGIN_EQUAL" => $login));
			if ($obUser->Fetch())
				$this->SetError("Такой логин уже существует", "login");
		}
		$password = $wizard->GetVar("password");
		if (strlen($password) < 6)
			$this->SetError("Пароль должен быть не меньше 6 символов", "password");
		$email = $wizard->GetVar("email");
		if (strlen($email) < 3 || !check_email($email))
			$this->SetError("Вы ввели неверный E-mail", "email");
	}
	function ShowStep()
	{
		$this->content .= '<table class="wizard-data-table">';
		$this->content .= '<tr><th align="right">Активен:</th><td>'.$this->ShowCheckBoxField("active", "Y").'</td></tr>';
		$this->content .= '<tr><th align="right"><span class="wizard-required">*</span>Логин (мин. 3 символа):</th><td>';
		$this->content .= $this->ShowInputField("text", "login", Array("size" => 25));
		$this->content .= '</td></tr>';
		$this->content .= '<tr><th align="right"><span class="wizard-required">*</span>Пароль (мин. 6 символов):</th><td>';
		$this->content .= $this->ShowInputField("password", "password", Array("size" => 25));
		$this->content .='</td></tr>';
		$this->content .= <tr><th align="right"><span class="wizard-required">*</span>E-mail:</th><td>';
		$this->content .= $this->ShowInputField("text", "email", Array("size" => 25));
		$this->content .= '</td></tr>';
		$this->content .= <tr><th align="right">Имя:</th><td>'.$this->ShowInputField("text", "user_name", Array("size" => 25)).'</td></tr>';
		$this->content .= '<tr><th align="right">Фамилия:</th><td>'.$this->ShowInputField("text", "user_surname", Array("size" => 25)).'</td></tr>';
		$this->content .= '</table>';
		$this->content .= '<br /><div class="wizard-note-box"><span class="wizard-required">*</span> Поля, обязательные для заполнения.</div>';
		$wizard =& $this->GetWizard();
		$formName = $wizard->GetFormName();
		$nextButton = $wizard->GetNextButtonID();
		$login = $wizard->GetRealName("login");
		$password = $wizard->GetRealName("password");
		$email = $wizard->GetRealName("email");
		$this->content .= <<<JS
			<script type="text/javascript">
            
				function CheckMainFields()
				{
					var form = document.forms["{$formName}"];
					if (!form)
						return;
					var login = form.elements["{$login}"].value;
					var password = form.elements["{$password}"].value;
					var email = form.elements["{$email}"].value;
					var error = "";
					if (login.length < 3)
						error += "Логин должен быть больше 3 символов.\\n";
					if (password.length < 6)
						error += "Пароль должен быть не меньше 6 символов.\\n";
					if (email.length < 3)
						error += "Вы ввели неверный E-mail.\\n";
					if (error.length > 0)
					{
						alert(error);
						return false;
					}
				}
				function AttachEvent()
				{
					var form = document.forms["{$formName}"];
					if (!form)
						return;
					var nextButton = form.elements["{$nextButton}"];
					if (!nextButton)
						return;
					nextButton.onclick = CheckMainFields;
				}
				if (window.addEventListener) 
					window.addEventListener("load", AttachEvent, false);
				else if (window.attachEvent) 
					window.attachEvent("onload", AttachEvent);
				//setTimeout(AttachEvent, 500); 
			</script>
JS;
	}
}
class AddtionalUserFields extends CWizardStep
{
	function InitStep()
	{
		//ID шага
		$this->SetStepID("additional_fields");
		//Заголовок
		$this->SetTitle("Дополнительные поля пользователя");
		$this->SetSubTitle("Введите дополнительные поля нового пользователя");
		//Навигация
		$this->SetPrevStep("main_fields");
		$this->SetNextStep("user_summary");
		$this->SetCancelStep("cancel");
		$wizard =& $this->GetWizard();
		$wizard->SetDefaultVar("group_id", "2");
	}
	function OnPostForm()
	{
		$this->SaveFile("photo", Array("max_file_size" => 1024*50, "extensions" => "gif,jpg,png"));
	}
	function ShowStep()
	{
		$wizard =& $this->GetWizard();
		$this->content .= '<table class="wizard-data-table">';
		$this->content .= '<tr><th align="right">Пол:</th><td>';
		$this->content .= $this->ShowRadioField("sex", "M", Array("id" => "sex_m")).'<label for="sex_m">Мужской</lable>';
		$this->content .= $this->ShowRadioField("sex", "F", Array("id" => "sex_f")).'<label for="sex_f">Женский</lable>';
		$this->content .= '</td></tr>';
		$this->content .= '<tr><th align="right">Фото<br />(max. 50кб, <br />JPG, GIF, PNG):</th><td>';
		$this->content .= $this->ShowFileField("photo", Array("size" => 25, "max_file_size" => 1024*50));
		$this->content .= "<br />".CFile::ShowImage($wizard->GetVar("photo"), 150, 150, "border=0", "", true);
		$this->content .= '</td></tr>';
		$obGroup = CGroup::GetList($by="name", $order="asc");
		$arSelectGroup = Array();
		while ($arGroup = $obGroup->Fetch())
			$arSelectGroup[$arGroup["ID"]] = htmlspecialchars($arGroup["NAME"]);
		$this->content .= '<tr><th align="right" valign="top">Группа:</th><td>';
		$this->content .= $this->ShowSelectField("group_id[]", $arSelectGroup , Array("multiple" => "multiple", "size" => "10"));
		$this->content .= '</td></tr>';
		$this->content .= '</table>';
	}
}
class UserSummary extends CWizardStep
{
	function InitStep()
	{
		$this->SetStepID("user_summary");
		//Заголовок
		$this->SetTitle("Создание пользователя");
		$this->SetSubTitle("Нажмите кнопку <i>Создать</i>, чтобы добавить нового пользователя");
		//Навигация
		$this->SetPrevStep("additional_fields");
		$this->SetNextStep("success");
		$this->SetNextCaption("Создать");
		$this->SetCancelStep("cancel");
	}
	function OnPostForm()
	{
		$wizard =& $this->GetWizard();
		if (!$wizard->IsNextButtonClick())
			return;
		//Добавляем пользователя
		$user = new CUser;
		$arFields = Array(
			"NAME" => $wizard->GetVar("user_name"),
			"LAST_NAME" => $wizard->GetVar("user_surname"),
			"EMAIL" => $wizard->GetVar("email"),
			"LOGIN" => $wizard->GetVar("login"),
			"ACTIVE" => ($wizard->GetVar("active") == "Y" ? "Y" : "N"),
			"GROUP_ID" => $wizard->GetVar("group_id"),
			"PASSWORD" => $wizard->GetVar("password"),
			"CONFIRM_PASSWORD" => $wizard->GetVar("password"),
			"PERSONAL_GENDER" => $wizard->GetVar("sex")
		);
		$photo = intval($wizard->GetVar("photo"));
		if ($photo > 0)
			$arFields["PERSONAL_PHOTO"] = CFile::MakeFileArray($photo) + Array("MODULE_ID" => "main");
		$userID = $user->Add($arFields);
		if (intval($userID) > 0)
		{
			$wizard->SetVar("userID", $userID);
			CFile::Delete($photo); //Удаляем временный файл
		}
		else
			$this->SetError($user->LAST_ERROR);
	}
	function ShowStep()
	{
		$this->content .= "Текущие настройки:<br /><br />";
		$wizard =& $this->GetWizard();
		$this->content .= "<i>Логин</i>: ".htmlspecialchars($wizard->GetVar("login"))."<br />";
		$this->content .= "<i>E-mail</i>: ".htmlspecialchars($wizard->GetVar("email"))."<br />";
		$user_name = $wizard->GetVar("user_name");
		if (strlen($user_name) > 0)
			$this->content .= "<i>Имя</i>: ".htmlspecialchars($user_name)."<br />";
		$user_surname = $wizard->GetVar("user_surname");
		if (strlen($user_surname) > 0)
			$this->content .= "<i>Фамилия</i>: ".htmlspecialchars($user_surname)."<br />";
		$sex = $wizard->GetVar("sex");
		if (strlen($sex) > 0)
			$this->content .= "<i>Пол</i>: ".($sex == "M" ? "Мужской": "Женский")."<br />";
		$photo = $wizard->GetVar("photo");
		if (intval($photo) > 0)
		{
			$this->content .= <i>Фото</i>:<br />";
			$this->content .= CFile::ShowImage($photo, 150, 150, "border=0", "", true);
		}
	}
}
class SuccessStep extends CWizardStep
{
	function InitStep()
	{
		//ID шага
		$this->SetStepID("success");
		//Заголовок
		$this->SetTitle("Работа мастера успешно завершена");
		//Навигация
		$this->SetCancelStep("success");
		$this->SetCancelCaption("Готово");
	}
	function ShowStep()
	{
		$this->content .= "Мастер успешно добавил нового пользователя. ";
		$wizard =& $this->GetWizard();
		$userID = intval($wizard->GetVar("userID"));
		if ($userID > 0)
			$this->content .= 'Идентификатор нового пользователя <a target="_blank" href="/bitrix/admin/user_edit.php?ID='.$userID.'&lang='.LANGUAGE_ID.'">'.$userID.'</a>';
	}
}
class CancelStep extends CWizardStep
{
	function InitStep()
	{
		$this->SetTitle("Мастер прерван");
		$this->SetStepID("cancel");
		$this->SetCancelStep("cancel");
		$this->SetCancelCaption("Закрыть");
	}
	function ShowStep()
	{
		$this->content .= "Мастер создания нового пользователя прерван. Новый пользователь не был создан.";
	}
}
?>

Статическое определение шагов в файле .description.php:

<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
$arWizardDescription = Array(
	"NAME" => "Мастер создания нового пользователя",
	"STEPS" => Array("MainUserFields", "AddtionalUserFields", "UserSummary", "SuccessStep", "CancelStep")
);
?>

Или динамическое определение в файле wizard.php:

<?
$wizard = new CWizardBase("Мастер создания нового пользователя", $package);
$wizard->AddSteps(Array("MainUserFields", "AddtionalUserFields", "UserSummary", "SuccessStep", "CancelStep"));
$wizard->Display();
?>


Пользовательские комментарии

Мы будем рады, если разработчики добавят свои комментарии по практическому использованию методов системы.

Для этого нужно всего лишь авторизоваться на сайте

Но помните, что Пользовательские комментарии, несмотря на модерацию, не являются официальной документацией. Ответственность за их использование несет сам пользователь.

Также Пользовательские комментарии не являются местом для обсуждения функционала. По подобным вопросам обращайтесь на форумы.
© «Битрикс», 2001-2024, «1С-Битрикс», 2024
Наверх