Ako upraviť formulár, aby pri disablovanej hodnote po submite vracal defaultValue?
- steelbull
- Člen | 241
Toto je len jeden z úplne jednoduchých formulárov, ale dôvod prečo sa to pýtam je, že mám oveľa väčší zložitejší formulár, ktorý ma veľa pravidiel na disablovanie inputov. Potom to zakaždým musím ošetrovať v modeli, či dané property vo values existujú. Nedá sa formulár nejako nastaviť tak, aby som mal po submite v modeli vždy všetky properties zo všetkých inputov aj disablovaných s tým, že ak budú disablované, vráti to default value? Potom by som mohol rovno inserovať/updatovať values z formulara bez toho aby som musel každú jednu hodnotu kontrolovať, či existuje? Príklad:
Formulár:
<?php
use Nette\Application\UI,
Nette\Database\Context,
Kdyby\Translation\Translator,
Nette\Security\User,
App\Model;
class UserFormFactory extends UI\Control
{
/** @var Context */
private $context;
/** @var Translator */
private $translator;
/** @var User */
private $user;
/** @var int */
private $id;
/** @var Model\UserGroupsModel */
private $mGroups;
/** @var Model\UsersModel */
private $mUsers;
/**
* Constructor.
*
* @param Context $context
* @param Translator $t
* @param User $u
*/
public function __construct(Context $context, Translator $t, User $u)
{
$this->context = $context;
$this->translator = $t;
$this->user = $u;
$this->mUsers = new Model\UsersModel($this->context);
$this->mGroups = new Model\UserGroupsModel($this->context, $this->user);
}
/**
* Method id
*
* @param $id
* @return $this
*/
public function id($id)
{
$this->id = $id;
return $this;
}
/**
* createComponentForm method.
*
* @return UI\Form
*/
public function createComponentForm()
{
$form = new UI\Form;
$t = $this->translator;
$disabled = $this->user->isInRole('administrators') ? false : true;
$form->getElementPrototype()->addAttributes(['id' => 'userForm', 'class' => 'k-form']);
$form->addText('sign', $t->translate('users.items.sign') . ':');
$form->addText('firstname', $t->translate('users.items.firstname') . ':')
->setRequired(true)
//->addRule(UI\Form::PATTERN, $t->trans('form.validator.pattern'), '^\p{L}+$')
->addRule(UI\Form::MIN_LENGTH, $t->translate('form.validator.more', array(1)), 1);
$form->addText('middlename', $t->translate('users.items.middlename') . ':')
->setRequired(false)
//->addRule(UI\Form::PATTERN, $t->trans('form.validator.pattern'), '^\p{L}+$')
->addRule(UI\Form::MIN_LENGTH, $t->translate('form.validator.more', array(1)), 1);
$form->addText('lastname', $t->translate('users.items.lastname') . ':')
->setRequired(true)
//->addRule(UI\Form::PATTERN, $t->trans('form.validator.pattern'), '^\p{L}+$')
->addRule(UI\Form::MIN_LENGTH, $t->translate('form.validator.more', array(1)), 1);
.....
$department_id = $form->addSelect('department_id', $t->translate('users.items.department_id') . ':',
(new Model\BaseListModel($this->context, $this->user))
->setTableName('app_user_departments')
->fetchPairs())
->setPrompt('');
$is_department_leader = $form->addCheckbox('is_department_leader', $t->translate('users.items.is_department_leader') . ':');
$form->addProtection();
if ($disabled) {
$department_id->setDisabled(true);
$group_id->setDisabled(true);
$is_department_leader->setDisabled(true);
if (!$this->id) {
$department_id->setDefaultValue($this->user->identity->department_id);
$group_id->setDefaultValue(2);
$is_department_leader->setDefaultValue(false);
}
}
if ($this->id) {
$data = $this->mUsers->getUser($this->id);
$form->setDefaults($data);
}
// Validate form
$form->onValidate[] = function ($form) {
$data = $form->getValues();
$t = $this->translator;
// Check, if username already exists
if ($data->login) {
if ($this->mUsers->checkUserExists($data->login, $this->id)) {
$form['login']->addError($t->translate('form.validator.login_exits'));
}
}
if (strlen($data->password) > 0) {
if (strlen($data->password) < 5) {
$form['password']->addError($t->translate('form.validator.more', array(5)));
} else {
if ($data->password != $data->password_verify) {
$form['password']->addError($t->translate('form.validator.pswd_not_match'));
$form['password_verify']->addError($t->translate('form.validator.pswd_not_match'));
}
}
} elseif (!$this->id) {
$form['password']->addError($t->translate('form.validator.required'));
}
};
// Submit form
$form->onSuccess[] = [$this, 'success'];
$form->onError[] = function () {
if ($this->presenter->isAjax()) {
$this->redrawControl('form');
}
};
return $form;
}
/**
* success method.
*
* @param $form
*/
public function success($form)
{
$data = $form->getValues();
if ($this->id) {
$data->id = $this->id;
} elseif (!$this->user->isInRole('administrators')) {
$data->group_id = 2;
$data->department_id = $this->user->identity->department_id;
$data->is_department_leader = false;
}
try {
$this->mUsers->saveUser($data);
if ($this->id) {
$this->presenter->flashMessage($this->translator->translate('users.items.updated'), 'success');
} else {
$this->presenter->flashMessage($this->translator->translate('users.items.created'), 'success');
}
$this->presenter->redirectBack();
} catch (\PDOException $ex) {
$this->presenter->flashMessage($ex->getMessage(), 'error');
$this->presenter->redrawControl('flash');
}
}
/**
* render method.
*/
public function render()
{
$this->template->setFile(__DIR__ . '/UserFormFactory.latte');
$this->template->render();
}
}
/**
* Interface IUserFormFactory
*/
interface IUserFormFactory
{
/**
* create method.
*
* @return UserFormFactory
*/
public function create();
}
Model:
public function saveUser($data)
{
$d = array(
self::COLUMN_SIGN => $data->sign,
self::COLUMN_FIRSTNAME => $data->firstname,
self::COLUMN_MIDDLENAME => $data->middlename,
self::COLUMN_LASTNAME => $data->lastname,
self::COLUMN_FULLNAME => $this->renderFullname($data->firstname, $data->lastname),
self::COLUMN_LOGIN => $data->login,
self::COLUMN_EMAIL => $data->email,
self::COLUMN_EMAIL_SEND => $data->email_send,
self::COLUMN_BLOCK => $data->block,
self::COLUMN_LANG_ID => $data->lang_id,
self::COLUMN_MAX_SATURATION => $data->max_saturation
);
if (isset($data->group_id)) {
$d[self::COLUMN_GROUP_ID] = $data->group_id;
}
// Da sa tomuto nejako vyhnut, ze ked tato polozka bude disablovana, vrati defaultValue?
if (isset($data->department_id)) {
$d[self::DEPARTMENT_ID] = $data->department_id;
}
// Da sa tomuto nejako vyhnut, ze ked tato polozka bude disablovana, vrati defaultValue?
if (isset($data->is_department_leader)) {
$d[self::IS_DEPARTMENT_LEADER] = $data->is_department_leader;
}
// Da sa tomuto nejako vyhnut, ze ked tato polozka bude disablovana, vrati defaultValue?
if (!empty($data->password)) {
$d[self::COLUMN_PASSWORD] = hash('sha1', $data->password);
}
if (!empty($data->id)) {
$this->context->table(self::TABLE_NAME)
->where(self::TABLE_ID, $data->id)
->update($d);
} else {
$d[self::COLUMN_REGISTER_DATE] = date('Y-m-d H:i:s');
return $result = $this->context->table(self::TABLE_NAME)
->insert($d)
->id;
}