checkbox checked při editaci uzivatele

andrstom
Člen | 21
+
0
-

Ahoj,

jsem nováčkem v nette a potřeboval bych radu. Mám formulař pro vložení uživatele. Uživatel má mimo jiné na výběr z několika „assays“ a pro každou „assay“ můžu nastavit „unit“. Dal jsem dokupy formulář, který mi to vloží do DB (budu rád za nápady, který i tento formulář zjednodušší), ale plácám se v tom, že bych chtěl uživatle upravit a nevím jak udělat to, aby se checkly odpovídající „assays“ a jejich „unit“. Problém bude asi i v presenteru – prostě jsem se do toho zamotal. Děkuju za každý nápad;-)

Presenter:

namespace App\Presenters;

use Nette;
use Nette\Application\UI\Form;
use Nette\Security\Identity;
use Nette\Security\Passwords;


class UserPresenter extends BasePresenter
{

    /**
     * @var Nette\Database\Context
     */
    private $database;

    public function __construct(Nette\Database\Context $database)
    {

        $this->database = $database;

    }

    public function renderAdd()
    {

        $users = $this->database->table('users')->order('id DESC');
        $this->template->userlist = $users;

        $assays = $this->database->table('assays');
        $this->template->assays = $assays;

        $units = $this->database->table('units');
        $this->template->units = $units;

    }

    public function renderEdit($userId)
    {
        $user = $this->database->table('users')->get($userId);
        if (!$user) {

            $this->error('Stránka nebyla nalezena');

        }

        $assays = $this->database->table('assays');
        $this->template->assays = $assays;

        $units = $this->database->table('units');
        $this->template->units = $units;

    }

    /**
     * Signup form factory.
     * @return Nette\Application\UI\Form
     */

    protected function createComponentUserAddForm()
    {

        $true_false = array('ANO'=>'ANO', 'NE'=>'NE');

        // load roles
        $roles = array('Admin'=>'Admin', 'Klient'=>'Klient');

        // load readers
        $readers = $this->database->table('reader')
                ->fetchPairs('id', 'reader_name');

        // load assays
        $assays = $this->database->table('assays')
                ->select('id, assay_short, assay_name, notice')->fetchAll();

        // load unitss
        $units = $this->database->table('units')
                ->select('id, unit_short, unit_name, notice')->fetchPairs('id', 'unit_name');


        $form = new Form;

        // Set Bootstrap 3 layout
        $this->makeStyleBootstrap3($form);

        // Set form labels
        $form->addText('login', 'Login: *')
                ->setRequired('Vyplňtě Login');

        $form->addText('username', 'Příjmení a Jméno: *')
                ->setRequired('Vyplňtě Příjmení a Jméno');

        $form->addText('email', 'E-mail: *', 55)
                ->setRequired('Vyplňte Email')
                ->addRule(Form::EMAIL, 'Neplatná emailová adresa');

        $form->addPassword('password', 'Heslo: *', 20)
                ->setOption('description', 'Alespoň 4 znaky')
                ->setRequired('Vyplňte Heslo')
                ->addRule(Form::MIN_LENGTH, 'Heslo musí mít alespoň %d znaků.', 4);

        $form->addPassword('password2', 'Heslo znovu: *', 20)
                ->addConditionOn($form['password'], Form::VALID)
                ->setRequired('Vyplňte Heslo znovu')
                ->addRule(Form::EQUAL, 'Hesla se neshodují.', $form['password']);

        $form->addRadioList('role_short', 'Vyberte roli: *', $roles)
                ->setRequired('Vyberte Roli');

        $form->addSelect('reader_id', 'Vyberte reader: *', $readers)
                ->setRequired('Vyberte Reader')
                ->setPrompt('Vyberte reader ...');

        $form->addText('company_name', 'Název firmy/laboratoře:');

        $form->addText('address', 'Adresa:');

        $form->addText('ico', 'IČO / DIČ:');

        $form->addText('gsm', 'Telefon:');

        $form->addTextArea('notice', 'Poznámka:');

        $form->addRadioList('print_detail', 'Tisk detailů na report:', $true_false)
                ->setDefaultValue('ANO')
                ->getSeparatorPrototype()->setName(null)
                ->setAttribute('style', "display:inline; margin-left: 5px");

        $form->addRadioList('active', 'Aktivní:', $true_false)
                ->setDefaultValue('ANO')
                ->getSeparatorPrototype()->setName(null)
                ->setAttribute('style', "display:inline; margin-left: 5px");

        foreach ($assays as $assay) {

            $form->addCheckbox('assay_'.$assay->id, $assay->assay_name);
            $form->addRadioList('unit_'.$assay->id, 'Jednotka', $units)
                    ->getSeparatorPrototype()->setName(null)
                    ->setAttribute('style', "display:inline; margin-left: 5px");

        }

        $form->addSubmit('send', 'Vložit');

        //call method signUpFormSucceeded() on success
        $form->onSuccess[] = [$this, 'userAddFormSucceeded'];

        return $form;

    }

    public function userAddFormSucceeded($form)
    {

        // get values from form
        $values = $form->getValues();

        try {

            // insert user details
            $row = $this->database->table('users')->insert([
                'username' => $values->username,
                'login' => $values->login,
                 ....
                'creator' => $this->getUser()->getIdentity()->getData()['username'],
                'created_at' => time(),
            ]);

            // get last inserted id
            $userLastId = $row->id;

            // get values from assays and units labels
            $assays = $form->getHttpData($form::DATA_TEXT | $form::DATA_KEYS, 'assay[]');

            foreach ($assays as $k => $v) {

                $units = $form->getHttpData($form::DATA_TEXT | $form::DATA_KEYS, 'unit[' . $k . '][]');

                // insert into db
                $this->database->table('users_assays')->insert([
                    'user_id' => $userLastId,
                    'assay_id' => $k,
                    'units_id' => $units,
                    'creator' => $this->getUser()->getIdentity()->getData()['username'],
                    'created_at' => time(),
                ]);

            }

        } catch (\Nette\Database\UniqueConstraintViolationException $e) {

                throw new DuplicateNameException;

        }

        // redirect and message
        $this->redirect('Settings:userlist');
        $this->flashMessage('Registrace byla úspěšná.');

    }

    public function actionEdit($userId)
    {
        if (!$this->getUser()->isLoggedIn()) {
            $this->redirect('User:in');
        }

        $assays = $this->database->table('assays');

        $user = $this->database->table('users')->get($userId);
        if (!$user) {

            $this->error('Uživatel nebyl nalezen');

        }

        $this['userAddForm']->setDefaults($user->toArray());

    }

}

šablona pro vložení uživatele (add.latte):

{block content}
<h2 n:block=title>Nový uživatel</h2>
<hr>

<form n:name=userAddForm class=form>
    <p>{label login}<input n:name=login /></p>
    <p>{label username}<input n:name=username /></p>
    ....
    <hr>
    <h3>Metody a jednotky:</h3>
    {foreach $assays as $assay}
        <hr>
        <p><label for={$assay->id}><input type=checkbox name="assay[{$assay->id}]" id={$assay->id} value={$assay->id}> {$assay->assay_name}</label></p>
        <p>
        {foreach $units as $unit}
            <label for={$assay->id}{$unit->id}><input type=radio name="unit[{$assay->id}][]" id={$assay->id}{$unit->id} value={$unit->id}> {$unit->unit_name}</label>
        {/foreach}
        </p>
    {/foreach}

    <p><input n:name=send class="btn btn-primary">

</form>

šablona pro editaci uživatele (edit.latte):

{block content}
<h2 n:block=title>Upravit uživatele</h2>
<hr>

<form n:name=userAddForm class=form>
    <p>{label login}<input n:name=login /></p>
    <p>{label username}<input n:name=username /></p>
    ...
    <hr>
    <h3>Metody a jednotky:</h3>

       !!! ... tady si nevím rady !!!

    <p><input n:name=send class="btn btn-primary">

</form>

Editoval andrstom (19. 9. 2017 22:12)

andrstom
Člen | 21
+
0
-

…tak jsem se s tim popral asi takto:

<?php
<form n:name=userForm class=form>
                <p>{label login}<input n:name=login /></p>
                <p>{label username}<input n:name=username /></p>
                <p>{label email}<input n:name=email /></p>
                <p>{label role_short}<radio n:name=role_short /></p>
                <p>{label reader_id}<select n:name=reader_id /></p>
                <p>{label company_name}<input n:name=company_name /></p>
                <p>{label address}<input n:name=address /></p>
                <p>{label ico}<input n:name=ico /></p>
                <p>{label gsm}<input n:name=gsm /></p>
                <p>{label notice}<textarea n:name=notice></textarea></p>
                <p>{label print_detail}<radio n:name=print_detail /></p>
                <p>{label active}<radio n:name=active /></p>
                <hr>
                <h3>Metody a jednotky:</h3>

                {foreach $assays as $assay}

                    {foreach $assay->related('users_assays') as $checked}{/foreach}

                    <!-- Checked inputs for user with assigned assays -->
                    {if $checked->users_id == $getUser->id}

                        <p><label for={$assay->id}><input type=checkbox name=assay[{$assay->id}] id={$assay->id} value={$assay->id}{if $checked->assays_id == $assay->id} checked="checked" {/if}> {$assay->assay_name}</label></p>

                        {foreach $units as $unit}
                            <label for={$assay->id}{$unit->id}><input type=radio name=unit[{$assay->id}][] id={$assay->id}{$unit->id} value={$unit->id}
                            {if $checked->assays_id == $assay->id}

                                {if $checked->units_id == $unit->id} checked="checked" {/if}

                            {/if} />{$unit->unit_name}</label>
                        {/foreach}

                    {else}
                        <!-- Empty inputs for user without assigned assays -->
                        <p><label for={$assay->id}><input type=checkbox name=assay[{$assay->id}] id={$assay->id} value={$assay->id} > {$assay->assay_name}</label></p>

                        {foreach $units as $unit}

                            <label for={$assay->id}{$unit->id}><input type=radio name=unit[{$assay->id}][] id={$assay->id}{$unit->id} value={$unit->id} />{$unit->unit_name}</label>

                        {/foreach}

                    {/if}
                    <hr>
                {/foreach}
            <p><input n:name=send class="btn btn-primary">
        </form>
?>

…treba by to nekdy nekdo pouzil.

andrstom
Člen | 21
+
0
-

Trapi me,ze mi nefunguje update (insert jede bez problemu):-( vidite nekdo chybu??? Cucham problem getParameter() pri zpracovani formulare?

Děkuju za kazdy tip.

<?php

.....

public function renderEdit($userId)
    {
        $getUser = $this->database->table('users')->get($userId);
        $this->template->getUser = $getUser;

        if (!$getUser) {

                $this->error('Uživatel nebyl nalezen!');

        }

        $assays = $this->database->table('assays');
        $this->template->assays = $assays;

        $units = $this->database->table('units');
        $this->template->units = $units;

    }

protected function createComponentUserForm()
    {

        $true_false = array('ANO'=>'ANO', 'NE'=>'NE');

        // set array of roles
        $roles = array('Admin'=>'Admin', 'Klient'=>'Klient');

        // load readers
        $readers = $this->database->table('reader')
                ->fetchPairs('id', 'reader_name');

        // load assays
        $assays = $this->database->table('assays')
                ->select('id, assay_short, assay_name, notice')->fetchAll();

        // load units
        $units = $this->database->table('units')
                ->select('id, unit_short, unit_name, notice')->fetchPairs('id', 'unit_name');


        $form = new Form;

        // Set Bootstrap 3 layout
        $this->makeStyleBootstrap3($form);

        // Set form labels
        $form->addText('login', 'Login: *')
                ->setRequired('Vyplňtě Login');

        $form->addText('username', 'Příjmení a Jméno: *')
                ->setRequired('Vyplňtě Příjmení a Jméno');

        $form->addText('email', 'E-mail: *', 55)
                ->setRequired('Vyplňte Email')
                ->addRule(Form::EMAIL, 'Neplatná emailová adresa');

        $form->addPassword('password', 'Heslo: *', 20)
                ->setOption('description', 'Alespoň 4 znaky')
                ->setRequired('Vyplňte Heslo')
                ->addRule(Form::MIN_LENGTH, 'Heslo musí mít alespoň %d znaků.', 4);

        $form->addPassword('password2', 'Heslo znovu: *', 20)
                ->addConditionOn($form['password'], Form::VALID)
                ->setRequired('Vyplňte Heslo znovu')
                ->addRule(Form::EQUAL, 'Hesla se neshodují.', $form['password']);

        $form->addRadioList('role_short', 'Vyberte roli: *', $roles)
                ->setRequired('Vyberte Roli');

        $form->addSelect('reader_id', 'Vyberte reader: *', $readers)
                ->setRequired('Vyberte Reader')
                ->setPrompt('Vyberte reader ...');

        $form->addText('company_name', 'Název firmy/laboratoře:');

        $form->addText('address', 'Adresa:');

        $form->addText('ico', 'IČO / DIČ:');

        $form->addText('gsm', 'Telefon:');

        $form->addTextArea('notice', 'Poznámka:');

        $form->addRadioList('print_detail', 'Tisk detailů na report:', $true_false)
                ->setDefaultValue('ANO')
                ->getSeparatorPrototype()->setName(null)
                ->setAttribute('style', "display:inline; margin-left: 5px");

        $form->addRadioList('active', 'Aktivní:', $true_false)
                ->setDefaultValue('ANO')
                ->getSeparatorPrototype()->setName(null)
                ->setAttribute('style', "display:inline; margin-left: 5px");

        $form->addSubmit('send', 'Uložit');

        //call method signUpFormSucceeded() on success
        $form->onSuccess[] = [$this, 'userFormSucceeded'];

        return $form;

    }


public function userFormSucceeded($form)
    {

        // get values from form
        $values = $form->getValues();

        $userId = $this->getParameter('userId');

        if ($userId) {
            $row = $this->database->table('users')->get($userId)->update([
                'username' => $values->username,
                'login' => $values->login,
                'email' => $values->email,
                'company_name' => $values->company_name,
                'address' => $values->address,
                'ico' => $values->ico,
                'gsm' => $values->gsm,
                'notice' => $values->notice,
                'role_short' => $values->role_short,
                'print_detail' => $values->print_detail,
                'reader_id' => $values->reader_id,
                'active' => $values->active,
                'editor' => $this->getUser()->getIdentity()->getData()['username'],
                'edited_at' => time(),
            ]);

        } else {

            try {

            // insert user details
            $row = $this->database->table('users')->insert([
                'username' => $values->username,
                'login' => $values->login,
                'email' => $values->email,
                'password' => Passwords::hash($values->password),
                'company_name' => $values->company_name,
                'address' => $values->address,
                'ico' => $values->ico,
                'gsm' => $values->gsm,
                'notice' => $values->notice,
                'role_short' => $values->role_short,
                'print_detail' => $values->print_detail,
                'reader_id' => $values->reader_id,
                'active' => $values->active,
                'creator' => $this->getUser()->getIdentity()->getData()['username'],
                'created_at' => time(),
            ]);

            // get last inserted id
            $userLastId = $row->id;

            // get values from assays and units labels
            $assays = $form->getHttpData($form::DATA_TEXT | $form::DATA_KEYS, 'assay[]');
            foreach ($assays as $k => $v) {

                $units = $form->getHttpData($form::DATA_TEXT | $form::DATA_KEYS, 'unit[' . $k . '][]');

                // insert into db
                $this->database->table('users_assays')->insert([
                    'users_id' => $userLastId,
                    'assays_id' => $k,
                    'units_id' => $units,
                    'creator' => $this->getUser()->getIdentity()->getData()['username'],
                    'created_at' => time(),
                ]);
            }

            } catch (\Nette\Database\UniqueConstraintViolationException $e) {

                throw new DuplicateNameException;

            }
        }

        // redirect and message
        $this->redirect('Settings:userlist');
        $this->flashMessage('Registrace byla úspěšná.');

}

public function actionEdit($userId)
    {
        if (!$this->getUser()->isLoggedIn()) {
            $this->redirect('User:in');
        }

        $user = $this->database->table('users')->get($userId);
        if (!$user) {

            $this->error('Uživatel nebyl nalezen');

        }

        $this['userForm']->setDefaults($user->toArray());

    }

....

?>
Šaman
Člen | 2632
+
-1
-

Proč si nepředáš to $userId přímo ve formuláři? Pak máš jistotu, že data ve formuláři se buď vztahují, nebo nevztahují k již existujícímu záznamu. Ukázka řešení tady: https://gist.github.com/…00f58376e76c
UserId přeneseš v hidden poli a při editaci jen nastavíš formuláři přednastavené hodnoty včetně $userId v metodě actionEdit($userId).
Takže u tebe by mělo stačit přidat to hidden pole a pak se řídit podle toho, jestli je, či není nastavené.

Editoval Šaman (24. 9. 2017 16:06)

andrstom
Člen | 21
+
0
-

…jo to me taky napadlo,ale prislo mi to zbytecny, kdyz mam userId uz v url. Jsem v nette uplnym novackem a sel jsem podle quickstartu, ktery jestli jsem to pochopil tak pri zpracovani formu ziskava hodnotu id metodou getParameter(), chci se naucit nove veci a tenhle zpusob mi prijde lepsi ?!?

chapu to to spravne,ze kdyz je v url …userId=3, tak
$userId = $this->getParameter(‚userId‘);
$userId = 3 ??

V mem pripade se neprovede update, i kdyz se zda ze podminku if($userId){…} splnuju

andrstom
Člen | 21
+
0
-

Kazdopadne diky za tip;-)

David Matějka
Moderator | 6445
+
0
-

Ahoj, chybu tam na prvni pohled nevidim.

Kdyz se kouknes na vygenerovany HTML, co obsahuje action u formulare?

jinak imho best practise je nacist si v action toho uzivatele do clenske promenne, nejak takhle:

private $user;

public function actionEdit($userId)
    {
        if (!$this->getUser()->isLoggedIn()) {
            $this->redirect('User:in');
        }

        $user = $this->database->table('users')->get($userId);
		$this->user = $user; //!!!
        if (!$user) {

            $this->error('Uživatel nebyl nalezen');

        }

        $this['userForm']->setDefaults($user->toArray());

    }
//a ve zpracovani pak jen
        // get values from form
        $values = $form->getValues();

        if ($user) {
            $user->update([
			...
		]);
		} else {
			//insert
		}
andrstom
Člen | 21
+
0
-

Diky zadalsi tip Davide. Zkusil jsem to podle tebe, ale taky bez uspechu. Problem budu mit asi jinde.

Jak se da vypsat HTML s tim action? Sorry, jsem fakt bažant:-)

David Matějka
Moderator | 6445
+
0
-

ctrl+u ti v prohlizeci zobrazi vygenerovane html.

Problem budu mit asi jinde.

to je mozne, zkus si dat treba do toho zpracovani nejaky kod pro debugovani, jako dump($this->user); exit; at zjistis, jestli se ten uzivatel nacetl..

andrstom
Člen | 21
+
0
-

Jo taaak, ja v tom hledal nejakou slozitost…:-DD…

Kdyz dumpnu dump($this->user) v actionEdit() tak mi to hodi toto:

Nette\Database\Table\ActiveRow #86a7
table private ⇒ Nette\Database\Table\Selection #2c14
data private ⇒ array (18)
id ⇒ 4
username ⇒ „demo3“ (5)
login ⇒ „demo3“ (5)
password ⇒ „…“ (60)
email ⇒ „andrsak85@gmail.com" (19)
company_name ⇒ ""
address ⇒ ""
ico ⇒ ""
gsm ⇒ ""
notice ⇒ ""
role_short ⇒ "Klient“ (6)
print_detail ⇒ „ANO“ (3)
reader_id ⇒ 4
active ⇒ „ANO“ (3)
creator ⇒ „admin“ (5)
created_at ⇒ 1506257063
editor ⇒ ""
edited_at ⇒ 0
dataRefreshed private ⇒ false
775.0 ms
User:edit
3.2 ms / 1
×

takze uzivatele nactenyho mam?!

Editoval andrstom (24. 9. 2017 20:09)

David Matějka
Moderator | 6445
+
0
-

jako i po odeslani formulare tam ta hodnota je, jo? a ve zpracovani se do dostane do te if vetve?

andrstom
Člen | 21
+
0
-

kdy dám:

<?php
public function userFormSucceeded($form)
{

    // get values from form
    $values = $form->getValues();

    dump($this->user);
    exit;

    if ($user) {
       // update
    } else {
       // insert
    }
}
?>

tak se mi nic nedumpne …

zkoušel jsem tu podminku i otočit if(!$user) {...} a insert to provedlo. Vypadá to, že to do podmínky leze.

…když jsem udělal chybu v zápisu např: fasdfasdf $row = $user->update([ ... ]); tak laděnka vyhodila chybu, ale když jsem udělal $row = $user->upda__([ ... ]); tak chybu nevyhodila, což je divný?!

nemůže být problém třeba s db tabulkama? špatně nastavené relace nebo tak něco?

Editoval andrstom (24. 9. 2017 20:53)

andrstom
Člen | 21
+
0
-

a HTML vypadá takto:

<?php
<form class=form action="/nette-test/www/user/edit?userId=4" method="post" id="frm-userForm">
	<p><label for="frm-userForm-login">Login: *</label><input type="text" name="login" class="form-control" id="frm-userForm-login" required data-nette-rules='[{"op":":filled","msg":"Vyplňtě Login"}]' value="demo2"></p>
	<p><label for="frm-userForm-username">Příjmení a Jméno: *</label><input type="text" name="username" class="form-control" id="frm-userForm-username" required data-nette-rules='[{"op":":filled","msg":"Vyplňtě Příjmení a Jméno"}]' value="demo"></p>

	...

	<p><input class="btn btn-primary" type="submit" name="send" value="Uložit">
	<input type="hidden" name="_do" value="userForm-submit">
</form>
?>
ali
Člen | 342
+
0
-

A jakou ti chybu ta ladenka vyhodila pri tom chybnem zapisu?

Editoval ali (24. 9. 2017 21:02)

David Matějka
Moderator | 6445
+
0
-

to fasdfasdf $row = $user->update([ ... ]) vyhodilo urcite nejaky parse error. pokud se nedumpne nic ani pred tou podminkou, tak se vubec nevola ta metoda pro zpracovani formulare.

andrstom
Člen | 21
+
0
-

ali, hodilo to syntax error, unexpected '$row' (T_VARIABLE) víceméně proto, že v tom blábolu nebyl středník…šlo mi v tomhle případě o to, abych zjistil jestli mi projde podmínka…ta projde ale vůvebc nedojde k update:-(

edit: jaj, ten parse error bude vlastně vždycky a nesouvisí s tou podmínkou O:-)

UserPresenter.php

<?php
namespace App\Presenters;

use Nette;
use Nette\Application\UI\Form;
use Nette\Security\Identity;
use Nette\Security\Passwords;

class UserPresenter extends BasePresenter
{

    private $user;

    /**
    * @var \App\Model\UserManager
    * @inject
    */
    public $userManager;

    /**
     * @var Nette\Database\Context
     */
    private $database;

    public function __construct(Nette\Database\Context $database)
    {
        $this->database = $database;
    }

    public function renderAdd() // pro vložení uživatele
    {

        $users = $this->database->table('users')->order('id DESC');
        $this->template->userlist = $users;

        $assays = $this->database->table('assays');
        $this->template->assays = $assays;

        $units = $this->database->table('units');
        $this->template->units = $units;

    }

    public function renderEdit($userId) // pro editaci uživatele
    {
        $getUser = $this->database->table('users')->get($userId);

        if (!$getUser) {
            $this->error('Uživatel nebyl nalezen!');
        }

        $assays = $this->database->table('assays');
        $this->template->assays = $assays;

        $units = $this->database->table('units');
        $this->template->units = $units;
    }

    protected function createComponentUserForm()
    {

        $true_false = array('ANO'=>'ANO', 'NE'=>'NE');

        // set array of roles
        $roles = array('Admin'=>'Admin', 'Klient'=>'Klient');

        // load readers
        $readers = $this->database->table('reader')
                ->fetchPairs('id', 'reader_name');

        // load assays
        $assays = $this->database->table('assays')
                ->select('id, assay_short, assay_name, notice')->fetchAll();

        // load units
        $units = $this->database->table('units')
                ->select('id, unit_short, unit_name, notice')->fetchPairs('id', 'unit_name');

        $form = new Form;
        $form->addText('login', 'Login: *')
                ->setRequired('Vyplňtě Login');
        $form->addText('username', 'Příjmení a Jméno: *')
                ->setRequired('Vyplňtě Příjmení a Jméno');
        $form->addText('email', 'E-mail: *', 55)
                ->setRequired('Vyplňte Email')
                ->addRule(Form::EMAIL, 'Neplatná emailová adresa');
        $form->addPassword('password', 'Heslo: *', 20)
                ->setOption('description', 'Alespoň 4 znaky')
                ->setRequired('Vyplňte Heslo')
                ->addRule(Form::MIN_LENGTH, 'Heslo musí mít alespoň %d znaků.', 4);
        $form->addPassword('password2', 'Heslo znovu: *', 20)
                ->addConditionOn($form['password'], Form::VALID)
                ->setRequired('Vyplňte Heslo znovu')
                ->addRule(Form::EQUAL, 'Hesla se neshodují.', $form['password']);
        $form->addRadioList('role_short', 'Vyberte roli: *', $roles)
                ->setRequired('Vyberte Roli');
        $form->addSelect('reader_id', 'Vyberte reader: *', $readers)
                ->setRequired('Vyberte Reader')
                ->setPrompt('Vyberte reader ...');
        $form->addText('company_name', 'Název firmy/laboratoře:');
        $form->addText('address', 'Adresa:');
        $form->addText('ico', 'IČO / DIČ:');
        $form->addText('gsm', 'Telefon:');
        $form->addTextArea('notice', 'Poznámka:');
        $form->addRadioList('print_detail', 'Tisk detailů na report:', $true_false)
                ->setDefaultValue('ANO')
                ->getSeparatorPrototype()->setName(null);

        $form->addRadioList('active', 'Aktivní:', $true_false)
                ->setDefaultValue('ANO')
                ->getSeparatorPrototype()->setName(null);

        $form->addSubmit('send', 'Uložit');

        //call method signUpFormSucceeded() on success
        $form->onSuccess[] = [$this, 'userFormSucceeded'];
        return $form;
    }

    public function userFormSucceeded($form)
    {
        $values = $form->getValues();

        if ($user) {
            $row = $user->update([
                'username' => $values->username,
                'login' => $values->login,
                'email' => $values->email,
                'company_name' => $values->company_name,
                'address' => $values->address,
                'ico' => $values->ico,
                'gsm' => $values->gsm,
                'notice' => $values->notice,
                'role_short' => $values->role_short,
                'print_detail' => $values->print_detail,
                'reader_id' => $values->reader_id,
                'active' => $values->active,
                'editor' => $this->getUser()->getIdentity()->getData()['username'],
                'edited_at' => time(),
            ]);

        } else {

            // insert user details
            $row = $user->insert([
                'username' => $values->username,
                'login' => $values->login,
                'email' => $values->email,
                'password' => Passwords::hash($values->password),
                'company_name' => $values->company_name,
                'address' => $values->address,
                'ico' => $values->ico,
                'gsm' => $values->gsm,
                'notice' => $values->notice,
                'role_short' => $values->role_short,
                'print_detail' => $values->print_detail,
                'reader_id' => $values->reader_id,
                'active' => $values->active,
                'creator' => $this->getUser()->getIdentity()->getData()['username'],
                'created_at' => time(),
            ]);

            // get last inserted id
            $userLastId = $row->id;

            // get values from assays and units labels
            $assays = $form->getHttpData($form::DATA_TEXT | $form::DATA_KEYS, 'assay[]');
            foreach ($assays as $k => $v) {

                $units = $form->getHttpData($form::DATA_TEXT | $form::DATA_KEYS, 'unit[' . $k . '][]');

                // insert into db
                $this->database->table('users_assays')->insert([
                    'users_id' => $userLastId,
                    'assays_id' => $k,
                    'units_id' => $units,
                    'creator' => $this->getUser()->getIdentity()->getData()['username'],
                    'created_at' => time(),
                ]);
            }
        }

        // redirect and message
        $this->redirect('Settings:userlist');
        $this->flashMessage('Registrace byla úspěšná.');
    }

    public function actionEdit($userId)
    {
        if (!$this->getUser()->isLoggedIn()) {
            $this->redirect('User:in');
        }

        $user = $this->database->table('users')->get($userId);
        $this->user = $user;

        if (!$user) {
            $this->error('Uživatel nebyl nalezen');
        }

        $this['userForm']->setDefaults($user->toArray());
    }
}
?>

Šablona edit.latte

<?php
{block content}
<h2 n:block=title>Upravit uživatele</h2>


<form n:name=userForm class=form>
	<p>{label login}<input n:name=login /></p>
	<p>{label username}<input n:name=username /></p>
	<p>{label email}<input n:name=email /></p>
	<p>{label role_short}<radio n:name=role_short /></p>
	<p>{label reader_id}<select n:name=reader_id /></p>
	<p>{label company_name}<input n:name=company_name /></p>
	<p>{label address}<input n:name=address /></p>
	<p>{label ico}<input n:name=ico /></p>
	<p>{label gsm}<input n:name=gsm /></p>
	<p>{label notice}<textarea n:name=notice></textarea></p>
	<p>{label print_detail}<radio n:name=print_detail /></p>
	<p>{label active}<radio n:name=active /></p>
	<hr>
	<h3>Metody a jednotky:</h3>
	{foreach $assays as $assay}
		{foreach $assay->related('users_assays') as $checked}{/foreach}
			<!-- Checked inputs for user with assigned assays -->
            {if $checked->users_id == $getUser->id}
				<p><label for={$assay->id}><input type=checkbox name=assay[{$assay->id}] id={$assay->id} value={$assay->id}{if $checked->assays_id == $assay->id} checked="checked" {/if}> {$assay->assay_name}</label></p>
				{foreach $units as $unit}
					<label for={$assay->id}{$unit->id}><input type=radio name=unit[{$assay->id}][] id={$assay->id}{$unit->id} value={$unit->id}
					{if $checked->assays_id == $assay->id}
						{if $checked->units_id == $unit->id} checked="checked" {/if}
					{/if} />{$unit->unit_name}</label>
				{/foreach}
			{else}
				<!-- Empty inputs for user without assigned assays -->
				<p><label for={$assay->id}><input type=checkbox name=assay[{$assay->id}] id={$assay->id} value={$assay->id} > {$assay->assay_name}</label></p>
				{foreach $units as $unit}
					<label for={$assay->id}{$unit->id}><input type=radio name=unit[{$assay->id}][] id={$assay->id}{$unit->id} value={$unit->id} />{$unit->unit_name}</label>
				{/foreach}
			{/if}
            <hr>
        {/foreach}
    <p><input n:name=send class="btn btn-primary">
</form>
?>

Editoval andrstom (24. 9. 2017 21:31)

andrstom
Člen | 21
+
0
-

David, nejspíš se nevolá, ale já nevim kde mám tu chybu…

David Matějka
Moderator | 6445
+
0
-

a nejsou ve formulari nejake errory pri validaci? jelikoz vidim, ze ho vykreslujes rucne, ale uz bez erroru. si tam dej do sablony pod {form} neco jako

<ul n:if="$form->hasErrors()">
	<li n:foreach="$form->errors as $error">{$error}</li>
</ul>
andrstom
Člen | 21
+
0
-

…no jasně…ta componenta (UserForm) je jak pro nového uživatele tak i pro update…a při insert tam je heslo a při update ne a tím to neprojde validací!!!

…zkusmo jsem v presenteru zakomentoval validaci password a laděnka hodila Undefined variable: user v userFormSucceeded($form) { … if ($user) { …

tak jsem to předělal na $this->user a jede to

PS: můžu to nějak obejít nebo mám vytvářet další komponentu, což mi příjde jako nosit dříví do lesa.

Editoval andrstom (24. 9. 2017 22:06)

David Matějka
Moderator | 6445
+
0
-

si tam to pole pro password pridej jen pokud neni vyplneno $this->user

andrstom
Člen | 21
+
+1
-

Myslíš něco jako:

<?php
if (!$this-user) {

    $form->addPassword('password', 'Heslo: *', 20)
         ->setOption('description', 'Alespoň 4 znaky')
         ->setRequired('Vyplňte Heslo')
         ->addRule(Form::MIN_LENGTH, 'Heslo musí mít alespoň %d znaků.', 4);

    $form->addPassword('password2', 'Heslo znovu: *', 20)
        ->addConditionOn($form['password'], Form::VALID)
        ->setRequired('Vyplňte Heslo znovu')
        ->addRule(Form::EQUAL, 'Hesla se neshodují.', $form['password']);
}
?>