Search code examples
phpcodeigniter-4

Codeigniter 4 unique name validation


My problem is that I have a modal and the input contains the value from the database. When I press the update button, the unique name validation check if the name already exists in the database. However, if I don't change it, it also checks the unique name validation, which I don't want to happen.

Here is the form.

<form action="<?= base_url('users/createRole'); ?> " method="post">
<div class="modal-body">
    <input type="hidden" name="roleID" id="roleID">
    <div class="mb-3">
        <label for="inputRoleName" class="form-label">Rolle hinzufügen</label>
        <input type="text" class="form-control" id="inputRoleName" name="inputRoleName" placeholder="Role Name">
    </div>
</div>
<div class="modal-footer">
    <button type="submit" class="btn btn-primary">Rolle speichern</button>
    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Schließen</button>
</div>
</form>
        $(".btnEditRole").click(function() {
            const roleID = $(this).data('id');
            const inputRoleName = $(this).data('role');
            $('#modalTitle').html('Update Data Role');
            $('.modal-footer button[type=submit]').html('Update rolle');
            $('.modal-content form').attr('action', '<?= base_url('users/updateRole') ?>');
            $('#roleID').val(roleID);
            $('#inputRoleName').val(inputRoleName);
            $('.modal').on('hidden.bs.modal', function() {
                location.reload(); // Refresh the page when modal is closed
            });
        });

Here is the Function.

public function updateRole()
{
if (!$this->validate(['inputRoleName' => ['rules' => 'is_unique[user_role.role_name]']])) {
    session()->setFlashdata('notif_error', '<b>Das Hinzufügen eines neuen Benutzers ist fehlgeschlagen</b> Der Benutzer existiert bereits! ');
    return redirect()->to(base_url('users'));
}
$updateRole = $this->userModel->updateRole($this->request->getPost(null, FILTER_UNSAFE_RAW));
if ($updateRole) {
    session()->setFlashdata('notif_success', '<b>Benutzerdaten erfolgreich aktualisieren</b> ');
    return redirect()->to(base_url('users'));
} else {
    session()->setFlashdata('notif_error', '<b>Benutzerdaten konnten nicht aktualisiert werden</b> ');
    return redirect()->to(base_url('users'));
}
}

Solution

  • When using unique values, you check them in this way:
    (this assumes your AutoIncrement/Primary is roleID

    For updating values
    change this:

    ['rules' => 'is_unique[user_role.role_name]']])) {
    

    to this:

    ['rules' => 'is_unique[user_role.role_name,roleID,{roleID}]])) {
    

    More information on placeholders can be found here: https://codeigniter.com/user_guide/libraries/validation.html?highlight=is_unique#validation-placeholders