KunLun
KunLun

Reputation: 3225

CodeIgniter4 - Redirect with data

I try to do this redirect in controller:

$this->getSession()->setFlashdata("error_controller", "Incorrect email or password");
return redirect()->route("login");

and this is in view:

<?php
    if($error_controller){
        echo "<div>" . $error_controller . "</div>";
    }else{
        echo "no-no";
    }
?>

In browser is printed no-no, which that means error_controller from flashdata not arrives to view.

How to redirect to login route with data?

Upvotes: 1

Views: 2777

Answers (2)

Pitshou
Pitshou

Reputation: 33

I tried this way and it worked:
In Controller:

$validate = $this->validate([
   'firstname' => 'required',
   'lastname'  => 'required',
   'email'     => 'required|valid_email|is_unique[users.email]',
]);

Then I passed errors as array in view (in controller)

$data['validation'] = $this->validator;
return view( 'view_file', $data );

Then in View File:

<?= form_open(....) ?>
  <input type="text" name="firstname" class="form-control" placeholder="Firstname">
  <?= ( isset($validation) && $validation->hasError('firstname')) ? $validation->getError('firstname'): ''; ?>
<?= form_close() ?>

Upvotes: 0

Welrico Dcosta
Welrico Dcosta

Reputation: 131

Add this code in the Controller

session()->setFlashData("error_controller","Incorrect email or password");

return redirect()->to(base_url('/login'));

Add this code inside the view file

 <?php

if(session()->has('error_controller'))
  echo "<div>" . session()->getFlashdata('error_controller') . "</div>";
    }else{
        echo "no-no";
    }
?>

Upvotes: 1

Related Questions