I want to validate three radio button inputs using codeigniter form validation rule:
HTML Page
<form action="<?php echo base_url('register')" ?> method="POST">
<input type="radio" name="cars" value="BMW">
<input type="radio" name="cars" value="Ferrari">
<input type="radio" name="cars" value="Jaguar">
<input type="submit" name="submitter">
</form>
Controller
public function register()
{
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
i know what to do here
}
else
{
i know what to do here
}
}
How to do form validation in codeigniter for radio button in my case ?
Load library for form validation and other helpers in application/config/autoload.php
$autoload['libraries'] = array('form_validation');
$autoload['helper'] = array('form', 'url');
In your controller
public function register()
{
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
echo "success";
}
else
{
$this->load->view('welcome_message');
}
}
In your view file use below code for printing validation errors
<?php echo validation_errors(); ?>
To show form error use form_error() function and to show all error use <?php echo validation_errors(); ?>
HTML PAGE
<form action="<?php echo base_url('register'); ?>" method="POST">
<?php echo form_error('cars'); ?>
<input type="radio" name="cars" value="BMW">
<input type="radio" name="cars" value="Ferrari">
<input type="radio" name="cars" value="Jaguar">
<input type="submit" name="submitter">
</form>
Controller
public function register(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
echo "i know what to do here"; //die;
}
else
{
echo "i know what to do here"; //die;
}
$this->load->view('welcome_message'); // your html view page
}
I think you are looking for in_list validation as an addition to required that has been mentioned by the others.
$this->form_validation->set_rules('cars', 'Cars', 'required|in_list[BMW,Ferrari,Jaguar]');
Also, as a self-reminder, since it took me 1 year to know about this.
Related
Controller
public function index()
{
//load session library
$this->load->library('session');
if($this->session->userdata('user')){
// redirect('home');
$this->load->view('heropage');
}
else{
$this->load->view('login_page');
}
}
public function login(){
$email = $_POST['email'];
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if($data)
{
$id=$data[0]->id;
$first_name=$data[0]->firstname;
$last_name=$data[0]->lastname;
$grade=$data[0]->grade;
$points=$data[0]->points;
$this->session->set_userdata('user_id',$id);
$this->session->set_userdata('lname',$last_name);
$this->session->set_userdata('user', $email);
$this->session->set_userdata('fname',$first_name);
$this->session->set_userdata('grade',$grade);
$this->session->set_userdata('pts',$points);
$this->getImg();
redirect('home');
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found'); }
}
View
<?php if(isset($_SESSION['success'])) :?>
<div class="alert alert-success"><?=$_SESSION['success'];?></div>
<?php endif; if(isset($_SESSION['error'])) :?>
<div class="alert alert-warning"><?=$_SESSION['error'];?></div>
<?php endif;?>
<!-- End alerts -->
<form action="<?php echo base_url();?>index.php/User/login" method="post" accept-charset="utf-8">
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="email" placeholder="Email">
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control"name="password" placeholder="Password">
<?php echo form_error('password'); ?>
</div>
<div class="form-group">
<button class="btn btn-sm btn-success" type="submit" align="center" name="login" class="submit">Log in</button>
</div>
</div>
</form>
model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email'=>$email));
if($query->num_rows() == 1 )
{
return $query->result();
}
}
Upon trying to log in, I got the error page cant be found. I want it to go to the home page if the session is correct. here is the error message:
404 Page Not Found
The page you requested was not found.
How can I solve the error because I have also set as needed in the routes
I think your form action should be <?php echo base_url(); ?>user/login
Also in your model you're not checking for password anywhere.
You're also not returning anything if the email is not found or more than 1 results are found -
($query->num_rows() == 1)
Model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email' => $email, 'password' => $password))->result(); // you should use row() here to return only 1 row.
return $query; // you should check the uniqueness of email on registration, not here -- not allow duplicate email on registration
}
Controller
public function login(){
$email = $_POST['email']; // $this->input->post('email');
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if( !empty($data) ) // if no result found it'll be empty
{
// your code
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found');
}
}
See, if this helps you.
I am trying to add a couple of custom toolbar buttons to my component, and at the moment the buttons are showing alright but can't get them to work.
My main problem is how to pass the id variable from the view layout to the sub-controller to perform a task in the case update a single column in the database.
These are my code structure
THE VIEW (view.html.php)
class LoanmanagerViewLoan extends JViewLegacy
{
protected $loanDetail;
public function display($tpl = null){
//Data from loanlist Model
$model=$this->getModel('Loan');
$this->loanDetail = $model->get_loan_detail();
$this->addToolbar();
parent::display($tpl);
}
protected function addToolbar()
{
// Get the toolbar object instance
$bar = JToolbar::getInstance('toolbar');
JToolBarHelper::Title(JText::_('Loan Details'));
//TRYING TO MAKE THIS BUTTON WORK
JToolBarHelper::custom('loan.approve', 'approve.png', 'icon-save.png', 'Approve Loan', false, false);
JToolBarHelper::custom('loan.deny', 'deny.png', 'deny.png', 'Deny Loan', false, false);
}
}
VIEW LAYOUT (tmpl/default.php)
JHtml::_('behavior.formvalidator');
<form action="<?php echo JRoute::_('index.php?option=com_loanmanager&view=loan&type=softloan&id='. (int) $loan->id); ?>" method="post" name="adminForm" id="loan-form" enctype="multipart/form-data">
<input type="hidden" name="option" value="com_loanmanager" />
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</form>
SUBCONTROLLER (controllers/loan.php)
class LoanmanagerControllerLoan extends JControllerLegacy
{
public function approve()
{
$jinput = JFactory::getApplication()->input;
$id = $input->post->get('id', 0, 'INT');
//Perform some SQL query with the $id
return parent::display();
}
}
you need to write an input with the id in the form itself.
<input type="hidden" name="id" value="<?= (int) $loan->id ?>" />
alternatively, don't get the id from post, as you have put it in the action get url of the form
$id = $input->getInt('id');
I'm trying to validate a form but it doesn't show validation errors and if field is empty, it saves. How to validate form?
My code is:
public function action_upload()
{
if($_POST) {
$name = array(
'name' => Arr::get($_POST, 'name')
);
$validate = Validation::factory($name)
->rule('name', 'not_empty');
try {
$save = Model_Offers::Save($this->user['user_id'], $name);
}
catch (ORM_Validation_Exception $e)
{
$result = $e->errors('models');
echo '<pre>';
print_r($result);
exit;
}
}
}
My view is:
<form id="myForm" action="<?php echo URL::base()?>user/upload" method="post" enctype="multipart/form-data">
<div class="input-group">
<label for="file">Name: </label>
<input type="text" name="name" id="name"><br>
</div>
</form>
You created the validation object, but you forgot to actually apply the rules you assigned. Simply do this by calling
$validate->check()
It'd be best to put this in an if-else statement
if($validate->check()){
//Save object
}
else{
//Get errors (use $validate->errors())
}
Hope that helps! :)
My code is to fetch questions of users saved in the database by a foreach loop and let the admin answer each question and save the answer of each question after checking of validation rules in the database , Here we go :
Model is :
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result();
}
My view is:
foreach ($questions as $id => $row) :
?>
<?php
echo "<h5>".$row->question;
echo "<br>";
echo "from : ".$row->user_name."</h5>";
echo date('Y-m-d H:i');
echo "<br>";
$q_no='save'.$row->id;
$ans_no='answer'.$row->id;
echo "<h4> Answer:</h4>";
echo form_open('control_panel');
?>
<textarea name='<?php echo 'answer'.$row->id; ?>' value="set_value('<?php echo 'answer'.$row->id; ?>')" class='form-control' rows='3'> </textarea>
<input type='hidden' name='<?php echo $q_no ; ?>' value='<?php echo $q_no; ?>' />
<input type='hidden' name='<?php echo $ans_no ; ?>' value='<?php echo $ans_no ; ?>' />
<?php
echo form_error($ans_no);
echo "
<div class='form-group'>
<div >
<label class='checkbox-inline'>
<input type='checkbox' name='add_faq' value='yes' />
Adding to FAQ page .
</label>
</div>
</div>
<p>";
?>
<input type='submit' name='<?php echo 'save'.$row->id; ?>' value='<?php echo 'save'.$row->id; ?>' class='btn btn-success btn-md'/>
<?php
echo 'answer'.$row->id;
?>
<hr>
<?php endforeach; ?>
and my controller is :
$this->load->model('control_panel');
$data['questions']=$this->control_panel->get_questions();
$data['no_of_questions']=count($data['questions']);
if($this->input->post($q_no))
{
$this->form_validation->set_rules($ans_no,'Answer','required|xss_clean');
if($this->form_validation->run())
{
/* code to insert answer in database */
}
}
of course it did not work with me :
i get errors :
Severity: Notice
Message: Undefined variable: q_no
i do not know how to fix it
I am using codeigniter as i said in the headline.
In your controller on your post() you have a variable called q_no you need to set variable that's why not picking it up.
I do not think name="" in input can have php code I think it has to be text only.
Also would be best to add for each in controller and the call it into view.
Please make sure on controller you do some thing like
$q_no = $this->input->post('q_no');
$ans_no = $this->input->post('ans_no');
Below is how I most likely would do lay out
For each Example On Controller
$this->load->model('control_panel');
$data['no_of_questions'] = $this->db->count_all('my_table');
$data['questions'] = array();
$results = $this->control_panel->get_questions();
foreach ($results as $result) {
$data['questions'][] = array(
'question_id' => $result['question_id'],
'q_no' => $result['q_no'],
'ans_no' => $result['ans_no']
);
}
//Then validation
$this->load->library('form_validation');
$this->form_validation->set_rules('q_no', '', 'required');
$this->form_validation->set_rules('ans_no', '', 'required');
if ($this->input->post('q_no')) { // Would Not Do It This Way
if ($this->form_validation->run() == TRUE) {
// Run Database Insert / Update
// Redirect or load same view
} else {
// Run False
$this->load->view('your view', $data);
}
}
Example On View
<?php foreach ($questions as $question) {?>
<input type="text" name="id" value="<?php echo $question['question_id'];?>"/>
<input type="text" name="q_no" value"<?php echo $question['q_no'];?>"/>
<input type="text"name="a_no" value="<?php echo $question['a_no'];?>"/>
<?php }?>
Model
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result_array();
}
I have created a login form with CodeIgniter. To test the form, I submit incorrect data, I get the correct information back and the form is redisplayed. If I correct the errors and resubmit the uri segment is appended to the URL.
So I call the app with localhost/myapp, the login form is displayed. On submission the url change to localhost/myapp/controller/authenticate. When submitting again the URL change to localhost/myapp/controller/authenticate/controller/authenticate
What is the problem here?
View
<form action="<?php echo base_url();?>/welcome/authenticate" method="post" id="loginfrm">
<input type="text" name="username" /><?php echo form_error('username', '<div class="error">', '</div>'); ?><br />
<input type="password" name="password" /><?php echo form_error('password', '<div class="error">', '</div>'); ?><br />
<input type="submit" value="Login" />
</form>
controller
public function index()
{
$this->load->view('welcome_message');
}
public function authenticate()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('welcome_message');
}
else
{
echo $this->input->post('username') . " -->> " . $this->input->post('password');
}
}
}
Always use redirect in function where forms are processed this prevents the form re-submission in your case if everything works fine and your view is loaded when user tries to refresh the page he will be asked to resubmit the form. Redirect function changes the url in browser address bar so user will no longer be asked for form re-submission.