Codeigniter form validation return always false - php

In my codeigniter controller function call $this->form_validation->run(), that return always false, and my validation_errors() not showing error, probably because not receive datas in post method...
my controller
class Reminder extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('reminder_model');
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->library('email');
$this->load->library('session');
if(!$this->session->auth_ok) {
redirect('auth/login');
}
}
public function index(){
$data['title'] = 'Reminder';
$data['section'] = 'reminder';
$data['reminders'] = $this->reminder_model->getReminders();
$data['operatori'] = $this->reminder_model->getOperators();
$this->form_validation->set_rules('selectUser','selectUser', '');
if($this->form_validation->run() === FALSE) {
$this->load->view('common/header2', $data);
$this->load->view('reminder/index', $data);
$this->load->view('common/footerReminder');
echo validation_errors();
}else{
echo "<pre>";
print_r($this->input->post());
die();
}
}
my view
<?php echo form_open('reminder/index'); ?>
<div class="form-group">
<label for="selectUser" style=" width: 30%">Utente: </label>
<select class="form-control" name="selectUser" id="selectUser" style="width: 30%">
<?php foreach($operatori as $operatore): ?>
<option value="<?php echo $operatore['ID']?>" <?php echo $r = ($operatore['ID']==$this->session->auth_user['ID']) ? 'selected' : '' ?>><?php echo $operatore['nome']." ".$operatore['cognome'] ?></option>
<?php endforeach; ?>
</select>
</div>
<button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> View</button>
<?php echo form_close(); ?>

In order to get the entire $_POST array using CodeIgniters built-in methods, you have to set the first parameter as NULL and the second parameter as TRUE
Like this:
$this->input->post(NULL, TRUE);
Also, you have not set any rules for validation..
In CodeIgniter, you set rules in the third parameter of the set_rules method within the form_validation object.
Like this:
$this->form_validation->set_rules($FIELD_NAME, $FIELD_NAME(for error messages), $RULES);
You would substitute the first $FIELD_NAME with the value of the name attribute on the HTML element you are looking to validate.
You would substitute the second $FIELD_NAME with the name you would like to use for the field when displaying an error message to the user.
You would substitute $RULES with the validation rules such as: 'required|min_length[#]|max_length[#]'
Hope this helps!

If you are not setting rules (which makes it rather pointless to use $this->form_validation->set_rules()) the form validation will fail as it's missing a required parameter.
If you don't need to validate a field, don't set a rule.
Try updating your set_rules instruction to $this->form_validation->set_rules('selectUser','selectUser', 'required'); to see if it behaves correctly. You can verify by filling something in the form (validation will pass) or leaving the field blank (validation will fail)
Just remember, if you won't set at least one validation rule for a field, don't instantiate the set_rules method for that field

Related

How to set custom message for custom validation in CI

I have three field in my html one is mobile_min,mobile_max and third field
i have taken is test which is a input field.So what i have to do i have to
create a custom validation with custom message in which my requirement is mobile_min value should not be greater than mobile_max value after submitting the from.So my code is working fine but i am getting this message "The Min value is not greater than max value field is required." and but i want this message "The Min value is not greater than max value field.".I have also read the custom message rule of CI but it is not working.
Html field code
<html>
<input type=text name=mobile_min>
<input type=text name=mobile_max>
<input type=hidden name=test>
</html>
Controller Validation code
<?php
if($this->input->post('mobile_min')>$this->input->post('mobile_max'))
{
$this->form_validation->set_rules('test', 'Min value is not greater than max value','trim|required');
}
?>
Please help me thanks in Advance.
Use codeigniter form validation call back https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods
Controller function:
<?php
class Controllername extends CI_Controller {
public function index() {
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('mobile_min', 'mobile min', 'required');
$this->form_validation->set_rules('mobile_max', 'mobile max', 'required|callback_somename');
if ($this->form_validation->run() == TRUE) {
/// Success data.
}
$this->load->view('some_view');
}
public function somename() {
if($this->input->post('mobile_min') > $this->input->post('mobile_max')) {
$this->form_validation->set_message('somename', 'Min value is not greater than max value');
return FALSE;
}
}
}
View
<?php echo form_open('controllername'); ?>
<?php echo validation_errors();?>
<?php echo form_input('mobile_min', '', array('id' => 'mobile_min'));?>
<?php echo form_input('mobile_max', '', array('id' => 'mobile_max'));?>
<button type="submit" class="btn btn-primary">Submit</button>
<?php echo form_close();?>

Stopping insertion to the database when the data already exists with Codeigniter

I'd like to know how to prevent an insert into a database when the data is already existing inside it. And how to make an onclick window with a message that alerts the user that the data they're inserting is already inside the database.
How I get inputs from my view goes a little bit like this:
<form method="post" action="<?php echo base_url();?>index.php/Controller/insertdata">
<h3>Select Course Code:</h3>
<select id="employeeid" name="empid">
<option value="" selected="selected">---Select Course Code---</option>
<?php foreach ($e_id as $row4): ?>
<option label="<?php echo $row4['EmpID']; ?>" value="<?php echo $row4['EmpID']; ?>" <?php echo set_select('course', $row4['EmpID'], False); ?>> <?php echo $row4['EmpID'] ; ?> </option>
<?php endforeach; ?>
</select>
<input type="Submit" value="Submit" id="submite_id">
It takes data from the database into the select tag. My database has Employee ID, Employee name, Dept. code, and assignment.
Here's my Controller:
public function insertdata() {
$this->model->setdata();
$data['results'] = $this->model->emp_all();
$this->load->view('edit_view', $data);
}
It inserts the data into the database and redirects the user to a view.
And finally here's how I insert it into the database in my Model:
public function setData(){
$f1 = $_POST['empid'];
$f2 = $_POST['empname'];
$f3 = $_POST['deptcode'];
$f4 = $_POST['assignment'];
$this->db->query("INSERT INTO employeeDB VALUES('$f1', '$f2', '$f3', '$f4')");
}
The catch is that the users should not be able to assign an employee id, and name to a duplicate assignment on the same department.
Any reply, comment, and insight will be appreciated. Thanks in advance!
You can use INSERT IGNORE INTO query. It won't insert record in table if data is already exists.
Please have look here.
Hope this will help.
You can use Codeingiter form_validation library.
$this->load->library('form_validation');
$this->form_validation->set_rules('empid', 'Employee ID', 'required|trim|employeeDB.empid');
Where the last Parameter employeeDB.empid is used as table_name.column_name. So your Controller will be as below.
public function insertdata() {
$this->load->library('form_validation');
$this->form_validation->set_rules('empid', 'Employee ID', 'required|trim|employeeDB.empid');
if ($this->form_validation->run() == FALSE) {
// Form Validation Failed.
$this->load->view('myform');
} else {
// Form Validation Passed.
$this->model->setData();
$data['results'] = $this->model->emp_all();
$this->load->view('edit_view', $data);
}
}
in sql server use can use NOTEXIST for protect to duplicate insertion

inserting a value in codeigniter shows no error

I am trying to insert a row to the db using codeigniter.
Model-post.php
class Post extends CI_Model{
function get_posts($num=20, $start=0){
$this->db->select()->from('posts')->where('active',1)->order_by('date_added','desc')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
function get_post($postid){
$this->db->select()->from('posts')->where(array('active' => 1, 'postID'=>$postid))->order_by('date_added','desc');
$query=$this->db->get();
return $query->first_row('array');
}
function insert_post($data){
$this->db->insert('posts',$data);
return $this->db->return_id();
}
Controller-posts.php
class Posts extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('post');
}
function index(){
$data['posts'] = $this->post->get_posts();
$this->load->view('post_index', $data);
}
function post($postid){
$data['post']=$this->post->get_post($postid);
$this->load->view('post',$data);
}
function new_post(){
if($_POST){
$data =array(
'title'=>$_POST['title'],
'post'=>$_POST['post'],
'active'=>1
);
$this->post->insert_post($data);
redirect(base_url());
}
else{
$this->load->view('new_post');
}
}
View-new_post.php
<form action="<?php base_url(); ?>posts/new_post" method="action">
<p>Title: <input type="text" name="title"></p>
<p>Description: <input type="textarea" name="post"></p>
<input type="submit" value="Add post">
</form>
Index view-post_index.php
foreach ($posts as $post) { ?>
<div id-="container">
<div><h3><?php echo $post['title']; ?> </h3>
<?php echo $post['post']; ?>
</div>
</div>
<?php
}
The index page shows all the posts from db. On clicking the title it takes to post.php view to show the respective data. This part is fine.
While trying to add a new post in new_post.php it is not reflecting in the db nor showing any error. Also I used redirect_url to redirect to the index page after inserting. So it shows the same available posts. On clicking the title it keeps on adding posts/post to the url repeatedly. Clicking the title once after redirecting the url shows
http://localhost/Codeigniter/posts/posts/post/1
Again on clicking the title it adds
http://localhost/Codeigniter/posts/posts/post/post/1
Can anyone help me? Thanks!
There are numerous issues across the entire application. These are what I found:
Views
Two problems in your new_post view.
You are not echoing out your base_url . You need to replace your form's action attribute.
the method attribute should either have post or get. In this case it should be post
Change it like this:
From this:
<form action="<?php base_url(); ?>posts/new_post" method="action">
To this:
<form action="<?= base_url(); ?>posts/new_post" method="post">
alternatively you can do this:
<form action="<?php echo base_url(); ?>posts/new_post" method="post">
Controller
In your posts controller, your new_post() function should be like this:
function new_post() {
if ($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'post' => $this->input->post('post'),
'active' => 1
);
$id = $this->post->insert_post($data);// this is the id return by your model.. dont know what you wann do with it
// maybe some conditionals checking if the $id is valid
redirect(base_url());
} else {
$this->load->view('new_post');
}
}
Model
function insert_post() should not have $this->db->return_id();, instead it should be $this->db->insert_id();
in your model
function insert_post($newpost){
$this->db->insert('posts',$newpost);
// check if the record was added
if ( $this->db->affected_rows() == '1' ) {
// return new id
return $this->db->insert_id();}
else {return FALSE;}
}
any user input must be validated. if you are using Codeigniter then use its form validation and use its input library like:
$this->input->post('title')
an example for blog posts are in the tutorial https://ellislab.com/codeIgniter/user-guide/tutorial/create_news_items.html
otherwise in your controller -- check if the new post id did not come back from the model -- if it did not come back then just go to an error method within the same controller so you don't lose the php error messages.
if ( ! $postid = $this->post->insert_post($newpost); ){
// passing the insert array so it can be examined for errors
$this->showInsertError($newpost) ; }
else {
// success now do something else ;
}

yii validate an input array of phone numbers

I'm working on a multiple contact form in Yii 1.1.16. Where the user can add multiple phone numbers.
Problem is, how would i validate this using Yii's rules()?
<div class="form-group">
<?php
echo $form->labelEx($model,'contacts', array('class'=>'col-md-3 control-label'));
?>
<div class="col-md-9">
<div class="multiple-contact multiple-form-group input-group padding-bottom-10px" data-max="5">
<div class="input-group-btn input-group-select">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="concept">Phone</span> <i class="fa fa-caret-down"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li>Phone</li>
<li>Fax</li>
<li>Mobile</li>
</ul>
<?php echo $form->textField($model,'contacts',array('type'=>'text', 'class'=>'input-group-select-val', 'name'=>'contacts[type][]','value'=>'phone')); ?>
</div>
<?php echo $form->textField($model,'contacts',array('size'=>60,'maxlength'=>255, 'name'=>'contacts[value][]','class'=>'form-control')); ?>
<?php echo $form->error($model,'contacts'); ?>
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-add"><i class="fa fa-plus"></i></button>
</span>
</div>
</div>
</div>
i tried using this, but doesn't work
public function rules()
{
return array(
array('contacts[value][]', 'required'),
array('contacts[value][]', 'integerOnly'=>true),
array('contacts[value][]','type','type'=>'array','allowEmpty'=>false)
);
}
Here is a sample Fiddle on how the jQuery side works. I want it to be able to validate with 'enableAjaxValidation'=>true,. Also, when more fields are added, it duplicates the id of the input. and no ajax post is done onblur/onfocus
Use custom validation.
Declare a custom validator in your rules, and define the validation you require in the validator method.
public function rules()
{
return array(
array('contacts', validateContacts),
);
}
public function validateContacts($attribute,$params)
{
if (length($this->contacts) == 0) {
$this->addError($attribute, 'You must add at least one contact!');
}
foreach($this->contacts as $contact) {
// ...
}
}
In your controller, assign the contacts array to the Model field and call the model's validation method. If there are any errors it will display through the line
<?php echo $form->error($model,'contacts'); ?>
in the view.
The controller contains the code to invoke the validation.
$contactModel = new Contact;
// assign the array of contacts to the model
$contactModel->contacts = $POST['myForm]['contacts']
$contactsModel->validate();
$this->render('myform', contactModel);
If you want the validation to happen through Ajax, you need to specify so when creating your form:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'top-websites-cr-form',
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit'=>true,
'validateOnChange'=>true),
));
In this case your controller can check for ajax forms.
if(isset($_POST['ajax']) && $_POST['ajax']==='branch-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
references:
http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/
You should make it a separate model with it's own validation.
Then in your controller you have to validate the main models and the related models separately.
Here is a good guide for such a setup:
http://www.yiiframework.com/wiki/384/creating-and-updating-model-and-its-related-models-in-one-form-inc-image/
To my opinion for best validation regarding phonenumbers you should use libphonenumber php library and there is an extension for it regarding yii framework here http://www.yiiframework.com/extension/libphonenumber/
basic usage:
Yii::setPathOfAlias('libphonenumber',Yii::getPathOfAlias('application.vendors.libphonenumber'));
$phonenumber=new libphonenumber\LibPhone($your_phone_number);
$phonenumber->validate();
for more details regarding usage and capabilities of libphonenumber php library you can find here:
https://github.com/davideme/libphonenumber-for-PHP
Let us consider you have a model called ContactNo and it looks like
class ContactNo extends CFormModel
{
public $contact;
public function rules()
{
return array(
// your rules
array('contact', 'required'),
array('contact','length','min'=>2)
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'contact'=>'Contact No',
);
}
}
The controller as SiteController and the action Name as actionIndex
Then your controller should look something like this
public function actionIndex()
{
// set how many contact fields you want here
$contactCount = 3;
$models = array();
if(isset($_POST['ContactNo']))
{
$successModels = 0;
foreach($_POST['ContactNo'] as $key=>$value)
{
$model = new ContactNo;
$model->attributes = $value;
if($model->validate()) // this validates your model
$successModels++; // it tells how many contact No.s have been validated
$models[$key]=$model;
}
// if all the contact nos are validated, then perform your task here
if($successModels === $contactCount)
{
// save your models
echo 'models saved';
Yii::app()->end();
}
}
else
{
for($index = 0;$index < $contactCount; $index++)
$models[] = new ContactNo;
}
$params = array();
$params['contactCount']=$contactCount;
$params['models']= $models;
$this->render('index',$params);
}
Now lets Go to view. Obviously the view is index.php and it will be something like
// Include all the initial part required for activeforms
<?php echo $form->errorSummary($models); ?>
<?php foreach ($models as $index=>$model): ?>
<div class="row">
<?php echo $form->labelEx($model,"[{$index}]contact"); ?>
<?php echo $form->textField($model,"[{$index}]contact",array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($model,"[{$index}]contact"); ?>
</div>
<?php endforeach; ?>
// Include the submit button
Hope this helps you or might give you an idea atleast to achieve your goal.

Form Validation error on Yii Framework?

I'm new on Yii, I have Try Crud and succes. now try to create validation but Still error.
here my script
Model:Buku.php
public function rules()
{
return array(
array('judul, penulis'),
array('judul', 'length','max'=>50),
array('penulis', 'length', 'max'=>50),
array('judul,penulis', 'on'=>'search'),
);
}
Controller: BukuController.php
public function actionCreate()
{
$model = new Buku;
if(isset($_POST['Buku']))
{
$model->judul =$_POST['Buku']['judul'];
$model->penulis =$_POST['Buku']['penulis'];
$model->save();
/*if($model->save())
{
Yii::app()->user->setFlash('Succes', "Data berhasil Disimpan");
$this->redirect(array('index'));
}*///end of
}//end if isset
$this->render('create',array('model'=>$model));
}//end of class
View: create.php
<div class="form">
<h2>Add Data</h2>
<?php echo CHtml::beginForm(array('buku/create'));?>
<?php
echo CHtml::errorSummary($model);
?>
<div class="row">
<?php echo CHtml::activeLabel($model,'judul');?>
<?php echo CHtml::activeTextField($model,'judul','');?>
<?php echo CHtml::errorSummary($model,'judul');?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'penulis');?>
<?php echo CHtml::activeTextField($model,'penulis','');?>
<?php echo CHtml::errorSummary($model,'penulis');?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit');?>
<?php echo CHtml::endForm();?>
</div>
</div>
the Error MEssage is
Buku has an invalid validation rule. The rule must specify attributes to be validated and the validator name
Anyone can Help This?
Im very appreciated Your answer.
Thanks
Pleas edit the first line, probably you wanted there 'required'
array('judul, penulis','required'),
And this is not needed:
$model->judul =$_POST['Buku']['judul'];
$model->penulis =$_POST['Buku']['penulis'];
instead you can use the mass-assignment: http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/
$model->attributes=$_POST['Buku'];
In Your Model class method rules first rule is invalid:
array('judul, penulis') -> no validation rule specified.
Try at least:
array('judul, penulis', 'required')
List of all Validation rules in Yii:
http://www.yiiframework.com/wiki/56/
How validation works
Parameters of a validator
Choice of validators
Scenarios
Validation rules reference
boolean : CBooleanValidator
captcha : CCaptchaValidator
compare : CCompareValidator
date : CDateValidator
default : CDefaultValueValidator
email : CEmailValidator
exist : CExistValidator
file : CFileValidator
filter : CFilterValidator
in : CRangeValidator
length : CStringValidator
numerical : CNumberValidator
match : CRegularExpressionValidator
required : CRequiredValidator
safe : CSafeValidator
type : CTypeValidator
unique : CUniqueValidator
unsafe : CUnsafeValidator
url : CUrlValidator
Selected readings
Built in validators in Yii....

Categories