Welcome Guest, Not a member yet? Register   Sign In
Shield validation question
#11

(08-15-2022, 03:47 AM)kenjis Wrote: What do you do in the page?
Can you show code?
Do you know why you call the recordActiveDate() method?

Here a part of the code:

PHP Code:
    public function itemCreatePost()
    {
        $validationRules['parent'] = ['label' => 'Padre''rules' => 'required|is_natural''errors' => ['is_natural' => 'Il valore specificato non è valido.']];

        foreach ($this->data['languages'] as $language)
        {
            $validationRules['name_' $language["slug"]] = ['label' => 'Nome''rules' => 'required|string|max_length[255]'];
            $validationRules['url_' $language["slug"]] = ['label' => 'Url''rules' => 'required|string|max_length[255]'];
        }

        if (!$this->validate($validationRules))
        {
            return redirect()->back()->withInput();
        }
        else
        {
            $data = [
                'menu_id' => $this->data['request']->getPost('menu_id'),
                'parent_id' => $this->data['request']->getPost('parent') != $this->data['request']->getPost('parent') : '0',
                'order_id' => $this->menuItemsModel->getNewOrder($this->data['request']->getPost('menu_id'), $this->data['request']->getPost('parent')),
                'icon' => $this->data['request']->getPost('icon') != '' $this->data['request']->getPost('icon') : '',
                'created_at' => date("Y-m-d H:i:s"),
                'created_by' => user_id()
            ];

            $item_id $this->menuItemsModel->insert($data);

            if ($item_id)
            {
                foreach ($this->data['languages'] as $lang)
                {
                    $data_translations[] = [
                        'item_id' => $item_id,
                        'language' => $lang['slug'],
                        'name' => $this->data['request']->getPost('name_' $lang['slug']),
                        'url' => $this->data['request']->getPost('url_' $lang['slug'])
                    ];
                }

                $this->menuItemsModel->insert_item_translations($data_translations);

                session()->setFlashdata('message', ['type' => 'alert-success''content' => 'La voce del menu è stata creata con successo.']);

                addToLog(user_id(), 'Creata voce menu <b>' $this->data['request']->getPost('name') . '</b>');

                return redirect()->to(session()->get('referer'));
            }
            else
            {
                session()->setFlashdata('message', ['type' => 'alert-danger''content' => 'Si è verificato un errore nell\'inserimento nel database.']);

                return redirect()->back()->withInput();
            }
        }
    

I don't call it directly, but it is invoked by shield, and the reason is explained in the configuration file.

PHP Code:
  
 
/**
    * --------------------------------------------------------------------
    * Record Last Active Date
    * --------------------------------------------------------------------
    * If true, will always update the `last_active` datetime for the
    * logged in user on every page request.
    */
    public bool $recordActiveDate true
Reply
#12

(This post was last modified: 08-15-2022, 03:29 PM by kenjis.)

Thank you.

I got the cause.

redirect()->withInput() saves validation errors in the Session.
And the check of the validation errors in Model (checkQueryReturn()),
$this->validation->getErrors() returns the errors in the Session.

I sent a PR https://github.com/codeigniter4/shield/pull/383
Reply
#13

(08-15-2022, 02:57 PM)kenjis Wrote: Thank you.

I got the cause.

redirect()->withInput() saves validation errors in the Session.
And the check of the validation errors in Model (checkQueryReturn()),
$this->validation->getErrors() returns the errors in the Session.

I sent a PR https://github.com/codeigniter4/shield/pull/383

Thanks to you for your patience, but I would never be able to solve it on my own.

Now I know I just have to wait for a fix.

Thanks again.
Reply
#14

(08-16-2022, 12:48 AM)chronic Wrote:
(08-15-2022, 02:57 PM)kenjis Wrote: Thank you.

I got the cause.

redirect()->withInput() saves validation errors in the Session.
And the check of the validation errors in Model (checkQueryReturn()),
$this->validation->getErrors() returns the errors in the Session.

I sent a PR https://github.com/codeigniter4/shield/pull/383

Thanks to you for your patience, but I would never be able to solve it on my own.

Now I know I just have to wait for a fix.

Thanks again.

Hi, you can solve like this:

Perform a pre-validation before save:

PHP Code:
        $rules $UserModel->getValidationRules();
        if (!$this->validateData($input$rules)) {
            return redirect()->back()->withInput()->with('errors'$this->validator->getErrors());
        
Reply
#15

(07-25-2022, 05:01 AM)janroz Wrote: Hello, I have question about shield for codeigniter 4. 
I have backend with form for edit and add new users. I use it like this:
PHP Code:
$this->validation->setRules([
    'username'        => 'is_unique[users.username,id,{user_id}]',
    'email'            => 'required|valid_email|unique_email[{user_id}]',
    'password'        => 'permit_empty|strong_password',
    'password_confirm' => 'matches[password]',
]);

if (!
$this->validation->withRequest($this->request)->run()) {
    return redirect()->back()->withInput()->with('errors'$this->validation->getErrors());
}
    

But when I submit a form, I expect to be redirected back to the form and show errors from validation. But I got CodeIgniter\Shield\Exceptions\ValidationException. 
I looked at sources and there is a trait for it - CheckQueryReturnTrait.
How to work with it, I just want to show validator errors like usual, but this throw exception and generate error.
Thank you.

Look at the validation rules: there is no rule for "unique_email" (except you wrote a custom role). Use instead the same as used in "username" (also "is_unique)
Reply




Theme © iAndrew 2016 - Forum software by © MyBB