Welcome Guest, Not a member yet? Register   Sign In
Modify users data as an admin
#1

I have installed Shield in my project. As an admin in the backoffice I would like to be able to modify user data if necessary. Can anyone give me an example of how this can be done? I used to write the Validation Rules in the model for every table, but for users there are two tables
Reply
#2

Try This lesson here https://shield.codeigniter.com/user_mana...ing_users/
Codeigniter First, Codeigniter Then You!!
yekrinaDigitals

Reply
#3

(This post was last modified: 04-27-2024, 11:10 AM by xsPurX.)

This sql query will give you a list of users, and you can use the user_id to make changes depending on what you want to do, if you need to update data in two tables just run two different update queries. Is that helpful enough or do you need some other examples? I am assuming you're using custom data, I don't know if the fill() option in shield will update custom fileds? Not sure about that.
Code:
        $users = $this->db->table('users, auth_groups_users,auth_identities')
->where('users.id = auth_groups_users.user_id')
->where('users.id = auth_identities.user_id')
->where('auth_identities.type', 'email_password')
->select('
users.id,
users.username,
users.status,
auth_groups_users.group,
auth_identities.secret
            ')
->orderBy('users.username', 'ASC')
->get();
return $users;
Reply
#4

(This post was last modified: 04-27-2024, 12:05 PM by padam.)

(04-26-2024, 04:56 PM)luckmoshy Wrote: Try This lesson here https://shield.codeigniter.com/user_mana...ing_users/

Hi luckmoshy. 
Thank you for the link. I am trying to use these examples there. The problem is that I do not know where to put in the UserModel the Validation Rules. The update works fine but if for example I erase the username I do not get an error message when I click save. The update is done even with an empty username!
Here is my code for the Controller. Just to mention the Users.php Controller lives into the Admin Module not in the app folder:

<?php

namespace Admin\Controllers;

use App\Controllers\BaseController;
use Admin\Models\UserModel;
use Codeigniter\Shield\Entities\User;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Exceptions\PageNotFoundException;

class Users extends BaseController
{

private UserModel $model;

public function __construct()
    {
        $this->model = new UserModel;

    }

public function index()
    {

$users = auth()->getProvider();
$myusers = $users->findAll();
    return view("Admin\Views\Users\index",[
"users"=>$myusers
]);
    }

public function show($id)  {
       
$session = \Config\Services:Confusedession();

$user = $this->getUserOr404($id);

        return view("Admin\Views\Users\show", [
            "user" => $user
        ]);
    }


public function edit($id)
    {
        $session = \Config\Services:Confusedession();
$session->set('recordmode', 'UPDATE');

$user = $this->getUserOr404($id);
        return view('Admin\Views\Users\edit', [
            "user" => $user
        ]);
    }


public function update($id)
    {
$users = auth()->getProvider();
        $user = $this->getUserOr404($id);
        $user->fill($this->request->getPost());
        if ( ! $user->hasChanged()) {
            return redirect()->back()
                            ->with("message", "Nothing to update.");
        }

   
if ($users->save($user)) {
            return redirect()->to("admin/users")
                            ->with("message", "user updated.");
        } else {
return redirect()->back()
                        ->with("errors", $this->model->errors())
                        ->withInput();
}
     
    }


public function delete($id)
    {
        $user = $this->getUserOr404($id);
        if ($this->request->is("post")) {
            $this->model->delete($id);
            return redirect()->to("admin")
                            ->with("message", "user deleted.");
        }

        return view("user/delete", [
            "user" => $user
        ]);
    }




public function remove($id)
    {
        $user = $this->getUserOr404($id);
if ($this->request->is("post")) {
          $this->model->delete($id);
            return redirect()->to("user")
                            ->with("message", "The record was deleted.");
        }
}

private function getUserOr404($id): User
    {
      $users = auth()->getProvider();
$user = $users->findById($id);
        if ($user === null) {
            throw new PageNotFoundException("User with id $id was not found");
        }
        return $user;
    }
}

(04-27-2024, 10:54 AM)xsPurX Wrote: This sql query will give you a list of users, and you can use the user_id to make changes depending on what you want to do, if you need to update data in two tables just run two different update queries. Is that helpful enough or do you need some other examples? I am assuming you're using custom data, I don't know if the fill() option in shield will update custom fileds? Not sure about that.
Code:
        $users = $this->db->table('users, auth_groups_users,auth_identities')
->where('users.id = auth_groups_users.user_id')
->where('users.id = auth_identities.user_id')
->where('auth_identities.type', 'email_password')
->select('
users.id,
users.username,
users.status,
auth_groups_users.group,
auth_identities.secret
            ')
->orderBy('users.username', 'ASC')
->get();
return $users;


Hello xsPurX. Thank you for trying to help me!

No, I am not using custom data in Shield.
I am using all the info about Shield in https://shield.codeigniter.com/user_management/managing_users/
In my Users.php Controller I have the method index which lists all the users in the db

<?php

namespace Admin\Controllers;

use App\Controllers\BaseController;
use Admin\Models\UserModel;
use Codeigniter\Shield\Entities\User;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Exceptions\PageNotFoundException;

class Users extends BaseController
{

private UserModel $model;

public function __construct()
    {
        $this->model = new UserModel;

    }

public function index()
    {

$users = auth()->getProvider();
$myusers = $users->findAll();
    return view("Admin\Views\Users\index",[
"users"=>$myusers
]);
    }

public function show($id)  {
       
$session = \Config\Services::session();

$user = $this->getUserOr404($id);

        return view("Admin\Views\Users\show", [
            "user" => $user
        ]);
    }


public function edit($id)
    {
        $session = \Config\Services::session();
$session->set('recordmode', 'UPDATE');

$user = $this->getUserOr404($id);
        return view('Admin\Views\Users\edit', [
            "user" => $user
        ]);
    }


public function update($id)
    {
$users = auth()->getProvider();
        $user = $this->getUserOr404($id);
        $user->fill($this->request->getPost());
        if ( ! $user->hasChanged()) {
            return redirect()->back()
                            ->with("message", "Nothing to update.");
        }

   
if ($users->save($user)) {
            return redirect()->to("admin/users")
                            ->with("message", "user updated.");
        } else {
return redirect()->back()
                        ->with("errors", $this->model->errors())
                        ->withInput();
}
     
    }


public function delete($id)
    {
        $user = $this->getUserOr404($id);
        if ($this->request->is("post")) {
            $this->model->delete($id);
            return redirect()->to("admin")
                            ->with("message", "user deleted.");
        }

        return view("user/delete", [
            "user" => $user
        ]);
    }




public function remove($id)
    {
        $user = $this->getUserOr404($id);
if ($this->request->is("post")) {
          $this->model->delete($id);
            return redirect()->to("user")
                            ->with("message", "The record was deleted.");
        }
}

private function getUserOr404($id): User
    {
      $users = auth()->getProvider();
$user = $users->findById($id);
        if ($user === null) {
            throw new PageNotFoundException("User with id $id was not found");
        }
        return $user;
    }
}

The index method in the controller gives the handle to the index.php view which works fine.
Then, I can click on the user name and I get the edit view if I want to modify any user data

<?= $this->extend("layouts/default") ?>

<?= $this->section("title") ?>Users - Record Modification<?= $this->endSection() ?>

<?= $this->section("content") ?>

<h1>Users - Record Modification</h1>

<?php if (session()->has("errors")): ?>

    <ul>
        <?php foreach(session("errors") as $error): ?>
            <li><?= $error ?></li>
        <?php endforeach; ?>
    </ul>

<?php endif; ?>



<?= form_open("admin/users/update/" . $user->id) ?>

<?= $this->include('Admin\Views\Users\form') ?>

</form>

<?= $this->endSection() ?>

---------------------------------------------------
And below is the form.php view
<h6>User</h6>

<label for="username">User Name</label>
<input type="text" id="username" name="username" value="<?= old("username", esc($user->username)) ?>">

<label for="email">Email</label>
<input type="email" id="email" name="email" value="<?= old("email", esc($user->email)) ?>">

<button >Save</button>

The Save Button works always even if there are errors i.e. username is empty.
No Validation Error messages are diaplayed.
QUESTION: How/Where can I write some Validation Rules and Validation messages. In usual cases with simple models with one table I use to write these inside the table's model. In Shield where things are different what shall I do?
Reply
#5

(This post was last modified: 04-27-2024, 01:42 PM by xsPurX.)

Can just wrap your edit() function to do an if around it, to reload the form if the validation is false, or go somewhere else if its good. Either that or in your update() whatever your form action is.

Code:
$validation = \Config\Services::validation();
        $rules = [
                'username' => 'required|max_length[30]',
                'emailaddress' => 'required|max_length[255]'
        ];
        if (! $this->validate($rules))
            {
            return view($layout, $this->data);
            }
        else
            {
            return redirect()->to('UsersAdmin');
            }
Reply




Theme © iAndrew 2016 - Forum software by © MyBB