Welcome Guest, Not a member yet? Register   Sign In
Codeigniter 4 form validation not working - something to do with action attribute
#1

I'm still getting to grips with Codeigniter 4 and I'm trying to overcome a form validation issue.

I keep hitting a brick wall with either losing `$_POST` data on submission, or reaching a 404 page does not exist error - and it all seems to centre on the `action` attribute of the form itself.

My Controller code:

Code:
public function index()
    {
    helper(['form', 'url']);
     
        $val = $this->validate([
            'name' => 'required'
        ]);

        if (! $val)
        {

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

        }
        else
        {
            return view('success');
        }
    }



My SignUp Controller:

Code:
<html>
<head>
    <title>My Form</title>
</head>
<body>

    <?= \Config\Services::validation()->listErrors(); ?>

    <form action="<?= site_url() ?>/form" method="post">

    <h5>Name</h5>
    <input type="text" name="name" value="" size="50" />

    <div><input type="submit" value="Submit" /></div>

    </form>

</body>
</html>


When the form is submitted with `<?= site_url() ?>/form` as its action, validation fails because `$_POST` is empty.
When the form is submitted with `<?= base_url() ?>/form` as its action, validation fails because `$_POST` is empty.
When I use Codeigniter's form method `<?php echo form_open(); ?>`, validation fails because `$_POST` is empty.
Same when I try `<?php echo form_open('form'); ?>`

These are the only ways every article and YouTube video I've watched on the subject has done it - without any issue.

When I change the code to this however... `<form action="" method="post">` - it WORKS! I am assuming this is only a fluke or a bug though.

It's not really suitable though because if I try to reroute the same Controller, I get:


Code:
$routes->get('form', 'Form::index'); // works with action=""

$routes->get('form/(:segment)', 'Form::index/$1'); // 404 file not found on submission with action=""
$routes->get('signup/form', 'Form::index'); // 404 file not found on submission with action=""


Could it just be a .htaccess issue? I have googled, but can't seem to find a clear answer.
Reply
#2

(This post was last modified: 05-03-2021, 10:40 AM by llyimo1920.)

Your route should use post method for form submission.
also it looks like form action is not defined
PHP Code:
$routes->post('...''...'); 

get method is used for retrieving data from the server
Reply




Theme © iAndrew 2016 - Forum software by © MyBB