I try to set up a password in a codeigniter form...
Everything seems ok to my eyes but no matter which password I use the form is still submitted...
here is the code in the controler:
class MyBlog extends Controller{
function MyBlog(){
parent::Controller();
$this->load->helper(array('url','form','html')); //here we load some classes that we use
$this->load->scaffolding('entries'); //scaffolfing is a feature that lets you add or remove elements from the database
$this->load->scaffolding('comments');
$this->load->library('form_validation');//load validation class used to validate our forms...
}
function index(){
$data['title'] = "My Blog Title"; //the title of my blog
$data['query'] = $this->db->get('entries'); //here we make a small query to entries table
$this->load->view('myBlog_view', $data); ///load all data variables on myBlog_view.php
//this is also for the form validation
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_rules('author', 'Author', 'required');
$this->form_validation->set_rules('pass', 'Pass', 'callback_pass_check');
function pass_check($str) {
if ($str == 'baywatch'){
return TRUE;
}
else{
return FALSE;
}
}
if ($this->form_validation->run() == TRUE)
{
$this->myBlog_insert();
//$this->load->view('formSuccess_view');
}
}
function myBlog_insert(){
$insert = array( 'title' => $_POST['title'],
'body' => $_POST['body'],
'author' => $_POST['author']
);
$this->db->insert('entries',$insert);
redirect('myBlog/');
}
}
and this is my form:
<div class="theForm">
<?php echo $this->form_validation->error_string; ?>
<?php echo validation_errors(); ?>
<?php echo form_open('myBlog'); ?>
<label for="title">Title:</label>
<input type='text' name="title" size="40" id="title" />
<p>
<label for="body">Body:</label>
<textarea name="body" rows = "10" cols="60" id="body"></textarea>
</p>
<p>
<label for="author">Author:</label>
<input type="text" name="author" size="40" id="author"/>
</p>
<p>
<label for="pass">Password:</label>
<input type="password" name="pass" size="38" id="pass"/>
</p>
<p><input type="submit" value="Submit New Post"/></p>
</form>
</div>
</body>
</html>
any ideas?
thanks in advance
<label for="pass">Password:</label>
<input type="text" name="pass" size="38" id="author"/>
The input type is text no password, the id='pass'.
Ok, a couple of things first:
1) id's should be unique. ie your author field and your password field shouldn't have the same id.
2) password fileds should use the type "password" not "text".
I think the reason you're having problems is with your callback function pass_check(). Try changing your function to:
function pass_check($pass)
{
if($pass !== 'baywatch')
{
return FALSE;
}
By the way, scaffolding has now been deprecated. Can I suggest you look into using models and the active record class as a way of interacting with your db? Also, this really isn't a very secure way of handling passwords. Have a look at some of the CI authentication libraries and see if you can implement one of them.
Ok guys...I found what the problem was...function pass_check was declared inside index()...and for some reason it needs to be outside as a method of the class...Hope this will help others... I give some ups for all the suggestions...
Related
I am trying to add the form error messages in my html form. Problem is there in first view. In user function html is disappear from where I start to use form_error(). My Original form design is like this: my original form
but after adding the form_error under the first input: my form error image
Here is my html code
<div class="form-group">
<label for="name"><i class="zmdi zmdi-account material-icons-name"></i></label>
<input type="text" name="username" id="name" placeholder="Your Name" />
<?php echo form_error('username','<p class="p_errror" id="name_error_p">','</p>') ?>
</div>
<div class="form-group">
<label for="email"><i class="zmdi zmdi-email"></i></label>
<input type="text" name="email" id="email" placeholder="Your Email"/>
<?php echo form_error('email','<p class="p_errror" id="name_error_p">','</p>') ?>
</div>
Here is my controller
<?php
class Register extends CI_Controller
{
public function user()
{
$this->load->view('files/registration/signup');
}
public function login()
{
$this->load->view('files/registration/login');
}
public function description()
{
$this->load->view('files/registration/description');
}
public function registerMe()
{
$this->load->helper('form','url');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|alpha|max_length[15]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('re_pass', 'Confirm Password', 'required|matches[pass]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run()===FALSE) {
$this->load->view('files/registration/signup');
}
else
{
$this->load->model('RegisterUser');
$this->RegisterUser->registerme($_POST);
}
}
}
?>
you need to load the form helper in signup function too. form_error is a function in form_helper. (this is required for other functions with a form view too)
public function user()
{
$this->load->helper('form');
$this->load->view('files/registration/signup');
}
html is disappeared because there was php error. check your error log when this happens or change codeigniter environment to development in index.php
I've exhausted all research endpoints (docs, Google, SO, etc.), so I've been driven to ask this question publicly. The very nature of my problem should have been solved by the CodeIgniter 3.0.6 official documentation in the section entitled "Adding Dynamic Data to the View" as I (think) I'm dealing with a variable never making the scope of my controller to be accessed by my view.
I'm adding a single, custom modification to a content publishing app consisting of an edit page fetching content by ID for table data update. 1st, the form;
EDIT.PHP
<div class="row">
<div class="col-md-12">
<h3>Update post</h3>
<form method="post" action="<?php echo base_url('post/update'); ?>" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" placeholder="News title" value="<?php echo $data['post']->title; ?>" class="form-control" />
</div>
<div class="form-group">
<label for="category">Category</label>
<select name="category" id="category" class="form-control">
<?php foreach($data['categories'] as $category): ?>
<option value="<?php echo $category->idcategory; ?>" <?php echo set_select('category', $category->idcategory); ?>><?php echo $category->title; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="image">Image</label>
<input type="file" name="image" id="image" class="form-control" placeholder="Upload an image" />
</div>
<div class="form-group">
<label for="body">Post detail</label>
<textarea name="body" id="body" class="form-control" placeholder="Provide news content. Basic HTML is allowed."><?php echo $data['post']->body; ?></textarea>
</div>
<div class="form-group">
<label for="tags">Tags</label>
<input type="text" name="tags" id="tags" value="<?php echo set_value('tags'); ?>" class="form-control" placeholder="Comma separated tags" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
I've edited the input values to target the values I need the form populated with in the cases of the Title and Post detail inputs (didn't need to alter anything for the category input, as it's a dropdown working brilliantly), and leaving the tags form input as is to not break output layout while I troubleshoot. Controller/function Post.php was duped from original 'add' function, and I'm including the entirety rather than what I feel is the problematic code chunk;
UPDATE FUNCTION
public function update($idpost) {
$this->load->helper('form');
$data['title'] = 'Update post | News Portal';
$data['post'] = $this->posts->get($idpost);
$this->load->model('category_model', 'cm');
$data['categories'] = $this->cm->get_all();
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'title', 'trim|required');
$this->form_validation->set_rules('body', 'post body', 'trim|required');
$this->form_validation->set_rules('tags', 'tags', 'required');
if($this->input->method(TRUE) == 'POST' && $this->form_validation->run()) {
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2000';
$config['max_width'] = '2000';
$config['max_height'] = '1200';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image')) {
$this->template->alert(
$this->upload->display_errors(),
'danger'
);
} else {
$upload_data = $this->upload->data();
$idpost = $this->posts->add(array(
'iduser' => $this->user->id(),
'title' => $this->input->post('title'),
'body' => $this->input->post('body'),
'image' => $upload_data['file_name']
));
$tags = $this->input->post('tags');
if(strlen($tags) > 0) {
$this->load->model('tag_model', 'tm');
$tags = explode(',', trim($tags));
$tags = array_map(array($this->tm, 'set_tag'), $tags);
$this->load->model('post_tag_model', 'ptm');
foreach($tags as $idtag) {
$this->ptm->add(array(
'idpost' => $idpost,
'idtag' => $idtag
));
}
}
$idcategory = $this->input->post('category');
if($idcategory) {
$this->load->model('post_category_model', 'pcm');
$this->pcm->add(array(
'idpost' => $idpost,
'idcategory' => $idcategory
));
}
$this->template->alert(
'Updated news item successfully',
'success'
);
redirect('post');
return;
}
}
$this->template->view('post/edit', $data);
}
This variable ($tags) is somehow lost between the controller and view, confirmed by using var_dump($this->_ci_cached_vars); to check all available objects within that corresponding view. I just need the variable $tags to repopulate with the data appropriate to the form input. How is it that there was no initialization of $tags within this function?
I COMPLETELY understand that the variable WILL NEVER be passed to the corresponding view because it's non-existant (as confirmed by my previous var_dump), but I'm lost as to how exactly to draw $tags within function scope so it can help form input to retrieve targeted data? All the other inputs are repopulating as needed. And, as an aside, I actually tracked down the original developer of this project and conferred with him on this. I tried to wrangle two approaches he outlined, but I ended up getting blank or erroring pages. The closest I could come theoretically to his second point - adapting a bit of code already in the news view partial;
<?php
if($tags = get_tags($data['news']->idpost)) {
echo '<div class="tags">';
echo 'Terms: ';
foreach($tags as $tag) {
echo ' <i class="fa fa-fw fa-link"></i> ' . $tag->title . ' ';
}
echo '</div>';
}
?>
which always ends in Undefined Index/Variable or some other damnable error message that I try to break my neck to solve, but just keep sinking further into the quagmire (lol!). It SEEMS simple to me, the basis of my problem, but I keep going around, and around, and around until I'm drunk dizzy and ten time more lost than I started out. Could someone provide a crumb of understanding?
I mean, I'm getting a conniption fit as it should be as simple as the answer provided here # Passing variable from controller to view in CodeIgniter. But, alas, 'tis not...thanks in advance for any clarificative leads.
#DFriend - I'm not wanting to alter the structure too much as ;
a) the code this is duped from is working and the only goal is to pull data from the appropriate table into that form input,
b) I don't want to disturb current functionality or inadvertently open another issue, and,
c) I'm trying to zero in on the correct elements.
Thank you for your time and answer, #DFriend.
I believe that the reason for your problems is because of the redirect call. By calling that you are essentially putting a new URL into the browser. Websites are stateless. Without using sessions or other means each request for a URL is unique. So by calling redirect you are wiping any knowledge of $tags from existence.
You can probably get around this by pushing $tags into the $_SESSION array and then checking for and retrieving it in the post controller.
Alternately, if post() is in the same controller you can simple call it instead of the redirect. post() will have be modified to accept an argument, or $tags will have to be a property of the controller class.
So to call directly to post, instead of
redirect('post');
return;
do this
$this->post($tags);
return;
Then define post to accept an optional argument
public function post($tags=null){
//somewhere in here
if(isset($tags)){
//$data is sent to views
$data['tags'] = $tags;
}
}
Expanded Answer:
How to implement a Post/Read/Get pattern in Codeigniter and still use field validation and repopulated form fields.
Using Codeigniter (CI) to implement a PRG pattern for processing requires an extension of the CI_Form_validation class. The code that follows should be in /application/libraries/MY_Form_validation.php
<?php
/**
* The base class (CI_Form_validation) has a protected property - _field_data
* which holds all the information provided by validation->set_rules()
* and all the results gathered by validation->run()
* MY_Form_validation provides a public 'setter' and 'getter' for that property.
*
*/
class MY_Form_validation extends CI_Form_validation{
public function __construct($rules = array())
{
parent::__construct($rules);
}
//Getter
public function get_field_data() {
return $this->_field_data;
}
//Setter
public function set_field_data($param=array()){
$this->_field_data = $param;
}
}
Without the template library you are using I fell back on $this->load->view(). And without access to your models and associated data I had to make some assumptions and, in some cases, leave db calls out.
Overall, I tried not to alter the structure too much. But I also wanted to demonstrate a couple handy uses of the form helper functions.
for the most part the restructuring I did was mostly an attempt at providing a clear example. If I succeed as showing the concepts you should be able to implement this fairly easily.
Here's the revised view. It makes more use of the 'form' helper functions.
<head>
<style>
.errmsg {
color: #FF0000;
font-size: .8em;
height: .8em;
}
</style>
</head>
<html>
<body>
<div class="row">
<div class="col-md-12">
<h3>Update post</h3>
<?php
echo form_open_multipart('posts/process_posting');
echo form_hidden('idpost', $idpost);
?>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" placeholder="News title" value="<?php echo $title; ?>" class="form-control" />
<span class="errmsg"><?php echo form_error('title'); ?> </span>
</div>
<div class="form-group">
<label for="category">Category</label>
<?php
echo form_dropdown('category', $categories, $selected_category, ['class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="image">Image</label>
<input type="file" name="image" id="image" class="form-control" placeholder="Upload an image" />
</div>
<div class="form-group">
<label for="body">Post detail</label>
<textarea name="body" id="body" class="form-control" placeholder="Provide news content. Basic HTML is allowed."><?php echo $body; ?></textarea>
<span class="errmsg"><?php echo form_error('body'); ?> </span>
</div>
<div class="form-group">
<label for="tags">Tags</label>
<input type="text" name="tags" id="tags" value="<?php echo $tags ?>" class="form-control" placeholder="Comma separated tags" />
<span class="errmsg"><?php echo form_error('tags'); ?> </span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<?= form_close(); ?>
</div>
</div>
</body>
</html>
The crux of this solution is to store form_validation->_field_data in the session when validation fails. The view loading function looks for a failure flag in session data and, if the flag is true, restores form_validation->_field_data to the current form_validation instance.
I tried to put a lot of explanation in the comments. What follows in the controller complete with display and processing methods.
class Posts extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->library('form_validation', NULL, 'fv');
}
/**
* post()
* In this example the function that shows the posting edit page
* Note the use of the optional argument with a NULL default
*/
function post($idpost = NULL)
{
$this->load->model('category_model', 'cm');
$categories = $this->cm->get_all();
/*
* Your model is returning an array of objects.
* This example is better served by an array of arrays.
* Why? So the helper function form_dropdown() can be used in the view.
*
* Rather than suggest changing the model
* these lines make the conversion to an array of arrays.
*/
$list = [];
foreach($categories as $category)
{
$list[$category->idcategory] = $category->title;
}
$data['categories'] = $list; // $data is used exclusivly to pass vars to the view
if(!empty($idpost))
{
//if argument is passed, a database record is retrieved.
$posting = $this->posts->get($idpost);
//Really should test for a valid return from model before using it.
//Skipping that for this example
$title = $posting->title;
$body = $posting->body;
//assuming your model returns the next two items like my made up model does
$selected_category = $posting->category;
$tags= $posting->tags;
}
else
//a failed validation (or a brand new post)
{
//check for failed validation
if($this->session->failed_validation)
{
// Validation failed. Restore validation results from session.
$this->fv->set_field_data($_SESSION['validated_fields']);
}
}
//setup $data for the view
/* The 'idpost' field was add to demonstrate how hidden data can be pasted to and from
* a processing method. In this case it would be useful in providing a 'where = $value'
* clause on a database update.
* Also, a lack of any value could be used indicate an insert is requried for a new record.
*
* Notice the ternary used to provide a default value to set_value()
*/
$data['idpost'] = $this->fv->set_value('idpost', isset($idpost) ? $idpost : NULL);
$data['title'] = $this->fv->set_value('title', isset($title) ? $title : NULL);
$data['body'] = $this->fv->set_value('body', isset($body) ? $body : NULL);
$data['tags'] = $this->fv->set_value('tags', isset($tags) ? $tags : NULL);
$data['selected_category'] = $this->fv->set_value('category', isset($selected_category) ? $selected_category : '1');
$this->load->view('post_view', $data);
}
public function process_posting()
{
if($this->input->method() !== 'post')
{
//somebody tried to access this directly - bad user, bad!
show_error('The action you have requested is not allowed.', 403);
// return; not needed because show_error() ends with call to exit
}
/*
* Note: Unless there is a rule set for a field the
* form_validation->_field_data property won't have
* any knowledge of the field.
* In Addition, the $_POST array from the POST call to the this page
* will be GONE when we redirect back to the view!
* So it won't be available to help repopulate the <form>
*
* Rather than making a copy of $_POST in $_SESSION we will rely
* completely on form_validation->_field_data
* to repopulate the form controls.
* That can only work if there is a rule set
* for ANY FIELD you want to repopulate after failed validation.
*/
$this->fv->set_rules('idpost', 'idpost', 'trim'); //added any rule so it will repopulate
// in this example required would not be useful for 'idpost'
$this->fv->set_rules('title', 'title', 'trim|required');
$this->fv->set_rules('body', 'post body', 'trim|required');
$this->fv->set_rules('tags', 'tags', 'required');
//add rule for category so it can be repopulated correctly if validation fails
$this->fv->set_rules('category', 'category', 'required');
if(!$this->fv->run())
{
// Validation failed. Make note in session data
$this->session->set_flashdata('failed_validation', TRUE);
//capture and save the validation results
$this->session->set_flashdata('validated_fields', $this->fv->get_field_data());
//back to 'posts/index' with server code 303 as per PRG pattern
redirect('posts/post', 'location', 303);
return;
}
// Fields are validated
// Do the image upload and other data storage, set messges, etc
// checking for $this->input->idpost could be used in this block
// to determine whether to call db->insert or db->update
//
// When process is finished, GET the page appropriate after successful <form> post
redirect('controller/method_that_runs_on_success', 'location', 303);
}
//end Class
}
Questions? Comments? Insults?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I am making a form for people to register but its not working, and for some reason my debugger in netbeans is not working so I cannot check properly.
This is the html form
<?php
if(validation_errors() != false)
{
echo '<div class="form-group alert alert-danger alert-box has-error">';
echo'<ul>';
echo validation_errors('<li class="control-label">', '</li>');
echo'</ul>';
echo '</div>';
}
/* form-horizontal */
echo form_open('main/insertInformation');
?>
<div class="form-group">
<input type="text" name="name" class="form-control input-lg" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control input-lg" placeholder="Email">
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control input-lg" placeholder="Phone">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control input-lg" placeholder="Password">
</div>
<div class="form-group">
<input type="password" name="password_confirm" class="form-control input-lg" placeholder="Confirm Password">
</div>
<div class="form-group">
<button type='submit' class="btn btn-primary btn-lg btn-block">Sign In</button>
</div>
</div>
Then I try to get all this information to my controller like this
public function insertInformation(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password_confirm', 'Password Confirm', 'required|matches[password]');
if ($this->form_validation->run() == FALSE){
$this->load->view('header_view');
$this->load->view('login_view');
$this->load->view('footer_view');
}else{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'password' => $this->input->post('password')
);
$this->db->trans_begin();
$this->load->model('main_page');
$this->main_page->storeRegisterInfo($data);
$message['account_created'] = 'Your account has been created';
$this->load->view('admin_view', $message);
}
}
And here is the model ,
public function storeRegisterInfo($data){
$insert = $this->db->insert('new_users',$data);
return $insert;
}
and my database looks like this
I am pretty new to codeigniter so I am pretty sure there is alot of errors here, so please do help me out and please do explain me in steps for a better understanding. Thanks!
THis is the error
After long discussion for specific for this error only you missed to load the model you need to load your model as:
$this->load->model('main_page');
UPDATE 1:
Removal of $this->db->trans_begin(); solved your problem but i think its not a complete solution.
If you want to use Transactions than make sure you can only apply this for InnoDB or BDB table types not for MyISAM.
If you are using InnoDB and want to use trans_begin() than make sure after execution of all queries you need to use trans_commit() otherwise this will not display anything in your database.
From the User Guide:
$this->db->trans_begin(); // transaction start
$this->db->query('AN SQL QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback(); // rollback if failure
}
else
{
$this->db->trans_commit(); // commit if success
}
Remove this part, all should work then
$this->db->trans_begin();
When we write an model file, we have set of conditions. One of that is model file should contain word of _model. (Ex: user_model, registration_model)
So your model should also be changed. Now your model looks like main_page change it, (ex: main_model, page_model).
File name should be Main_model.php
Inside your model
class Main_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
}
This is how Codeigniter use the Model.
I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.
I have a register_page.php file in the views folder which is just a register form. When you click the register button, and say the password doesn't match, it should that the password doesn't match after clicking the submit button. However, after you type the password and it still doesn't match, it doesn't do anything, it just duplicates the url.
For example
URL when the password doesn't match: http://localhost/dayone/user/register_user
URL when when the password still doesn't match: http://localhost/dayone/user/user/register_user
At this point, the form is empty, all the values are removed and when you press enter without filling anything in, it doesn't show any error, but the URL says: http://localhost/dayone/user/user/register_user
What's causing this?
My user.php controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function index()
{
$this->load->view('includes/header');
$this->load->view('register_page');
$this->load->view('includes/footer');
}
public function register_user () {
$this->load->library('form_validation');
//rules to become a registered user
$this->form_validation->set_rules('first_name', 'First Name', 'required|trim|min_length[3]|max_length[20]|xss_clean');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|min_length[3]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'required|trim|min_length[6]|max_length[50]|valid_email|is_unique[users.email]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[6]|max_length[50]|matches[password_conf]|xss_clean');
$this->form_validation->set_rules('password_conf', 'Confirm Password', 'required|trim|min_length[6]|max_length[50]|xss_clean');
if ($this->form_validation->run() == FALSE) {
//user didn't validate, send back to login form and show errors
$this->load->view('includes/header');
$this->load->view('register_page');
$this->load->view('includes/footer');
} else {
//successful registration
$this->load->view('login');
}
}
}
My resister_page.php (with the register form):
<!DOCTYPE html>
<html lang="en">
<body>
<div id="container" class="page">
<div>
<section class="container">
<h2 class="block-title block-title--bottom">Login</h2>
<div class="login">
<?php echo validation_errors('<p class="alert-market">'); ?>
<form class="contact" id="contact-form" name="contact-form" method="post" action="user/register_user">
<!--- FIRST NAME --->
<input class="contact__field" value="<?php echo set_value('first_name'); ?>" name="first_name" id="first_name" type="text" placeholder="First Name">
<!--- LAST NAME --->
<input class="contact__field" value="<?php echo set_value('last_name'); ?>" name="last_name" id="last_name" type="text" placeholder="Last Name">
<!--- EMAIL --->
<input class="contact__field" value="<?php echo set_value('email'); ?>" name="email" id="email" type="email" placeholder="Email">
<!--- PASSWORD --->
<input class="contact__field" name="password" id="password" type="password" placeholder="Password">
<!--- CONFIRM PASSWORD --->
<input class="contact__field" name="password_conf" id="password_conf" type="password" placeholder="Confirm Password">
<a class="login__callback" href="#">Forgot password?</a>
<input class="btn btn--decorated btn-warning login__btn" value = "Login" name="submit" type="submit">
<?php echo form_close(); ?>
</div>
</section><!-- end container -->
</div>
</div><!-- /#page -->
</body>
</html>
I have no idea what is causing this.
Instead of this one:
<form class="contact" id="contact-form" name="contact-form" method="post" action="user/register_user">
You can use this one:
<?php echo form_open('user/register_user');?>
Which is also equal to this:
<form method="post" accept-charset="utf-8" action="http://localhost/dayone/user/register_user"/>
Assuming that your base_url in your config.php is equal to:
$config['base_url'] = 'http://localhost/dayone/';
I suggest you invest time in reading more about CodeIgniter's User Guide here.
EDIT:
Do not forget to load your form and url helpers too. You can load them in autoload.php in application/config
$autoload['helper'] = array("url","form");
Or
Make a function __contruct() and load your helpers and models there.
Example:
function __construct()
{
parent::__construct();
$this->load->model('sample_model');
$this->load->helper('url');
$this->load->helper('form');
}
Constructors are useful if you need to set some default values, or run
a default process when your class is instantiated. Constructors can't
return a value, but they can do some default work.
--From CodeIgniter - Controllers under Class Constructors
First use form helper to form open
<?php echo form_open('user/register_user');?>
Then change your match password rules like(match confirm password to password):-
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[6]|max_length[50]|xss_clean');
$this->form_validation->set_rules('password_conf', 'Confirm Password', 'required|trim|min_length[6]|max_length[50]|matches[password]|xss_clean');
Then your else part should be a redirect not load a view again like
else {
// success register
redirect('login');
}