i try to validate my form, but it always return with FALSE. The form fill the POST variable, the validation config is setted up, but it don't work. I tried everything, and now i stucked. Maybe your eyes catch the error.
Here is my controller:
public function new_pass()
{
$code = mysql_real_escape_string($this->uri->segment(3));
$this->load->model('forgot_password_model');
if($this->forgot_password_model->check_code($code))
{
if($this->input->post('submit'))
{
$this->new_pass_validation();
}
else
{
$this->new_pass_form();
}
}
else
{
redirect('welcome');
}
}
private function new_pass_validation()
{
$this->load->library('form_validation');
var_dump($this->form_validation->run('forgot_password/new_pass'));
var_dump($this->input->post());
if ($this->form_validation->run() === FALSE)
{
// print_r('dump' . validation_errors());
$this->new_pass_form();
}
else
{
}
}
The config/form_validation:
$config = array(
'forgot_password/new_pass' => array(
array(
array(
'field' => 'password',
'label' => lang('default_jelszo'),
'rules' => 'trim|required|min_length[5]|max_length[32]'
),
array(
'field' => 'repassword',
'label' => lang('default_jelszo_megerosites'),
'rules' => 'trim|required|matches[password]|callback_password_hash'
),
)
),
);
And the view:
<section id="content">
<a id="logo" href=""></a>
<?=validation_errors(); ?>
<div class="formwrapp">
<form action="<?=site_url() . $this->uri->uri_string(); ?>" method="post">
<h3>Forgot password</h3>
<ul>
<li>Pass</li>
<li><input type="password" value="" name="password" /></li>
<li>Repass</li>
<li><input type="password" value="" name="repassword" /></li>
<li> </li><li><input id="login" type="submit" value="Submit" name="submit" /></li>
</ul>
</form>
</div>
</section>
You have an unnecessary array in your config file, try:
$config = array(
'forgot_password/new_pass' => array(
array(
'field' => 'password',
'label' => lang('default_jelszo'),
'rules' => 'trim|required|min_length[5]|max_length[32]'
),
array(
'field' => 'repassword',
'label' => lang('default_jelszo_megerosites'),
'rules' => 'trim|required|matches[password]|callback_password_hash'
)
)
);
I think the best way to do the job as your is to follow this link ... i.e. without using config type but if u want to use config i think u had forgot to write the code ...
$this->form_validation->set_rules($config);
http://ellislab.com/codeigniter%20/user-guide/libraries/form_validation.html
Related
I don't know where I got wrong but I couldn't find it out.
I have a form validation with a callback file check validation function
My Add_Post Function:
public function add_post()
{
$validation = array (
array(
'field' => 'post_title',
'label' => 'Post title',
'rules' => 'trim|required|alpha_numeric'
),
array(
'field' => 'headerimage',
'rules' => 'required|callback_file_check'
),
array(
'field' => 'post_desc',
'label' => 'Post Description',
'rules' => 'trim|required|alpha_numeric'
),
array(
'field' => 'post_content',
'label' => 'Post content',
'rules' => 'trim|required'
)
);
$this->form_validation->set_rules($validation);
if($this->form_validation->run()===FALSE)
{
$info['errors'] = validation_errors();
$info['success'] = false;
}
else
{
$config = array(
"upload_path" => "./uploads/blog_images",
"max_size" => "2048000",
"allowed_types"=> "gif|png|jpg|jpeg",
"file_name" => 'header_'.substr(md5(rand()),0,7),
"overwrite" => false
);
$this->load->library('upload', $config);
if($this->upload->do_upload('file'))
{
$uploadFile = $this->upload->upload_data();
$uploadFileName = $uploadFile['file_name'];
$data = array(
"post_title" => $this->input->post('post_title'),
"post_content" => $this->input->post('post_content'),
"post_image" => $uploadFileName,
"post_created" => $this->input->post('time')
);
$this->Blog_model->add_post($data);
}
$info['success'] = true;
$info['message'] = "Successfully added blog post";
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
Callback function:
public function file_check($str){
$allowed_mime_type_arr = array('application/pdf', 'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');
$mime = get_mime_by_extension($_FILES['headerimage']['name']);
if(isset($_FILES['headerimage']['name']) && $_FILES['headerimage']['name'] != "") {
if(in_array($mime, $allowed_mime_type_arr)) {
return true;
} else {
$this->form_validation->set_message('file_check', 'Please select only pdf/gif/jpg/png file.');
return false;
}
} else {
$this->form_validation->set_message('file_check', 'Please choose a file to upload.');
return false;
}
}
Here's for the view part:
<?php echo form_open_multipart('Blog/file_check',array("class"=>"form-horizontal","id"=>"blogform")); ?>
<div class="row">
<div class="col-md-6">
<input type="text" placeholder="Enter your post title" name="post_title" class="form-control">
</div>
<div class="col-md-6 form-group">
<label for="file" class="control-label col-md-4">Select header image:</label>
<div class="col-md-8">
<input type="file" name="headerimage" id="file" accept="image/*" />
</div>
</div>
</div>
<input type="text" placeholder="Enter your post description" name="post_desc" class="form-control">
<label class="control-label text-muted">Post Body:</label>
<div>
<textarea id="post_content" name="content"></textarea>
</div>
<button class="btn btn-default pull-right" type="button" id="save-post"><i class="fa fa-save"></i> Save Post</button>
<div class="clearfix"></div>
<?php echo form_close(); ?>
My Ajax code:
$(document).on('click','#save-post',function(){
$post_content = $('#post_content').summernote('code');
$time = $('#time').text();
$.ajax({
url:site_url('Blog/add_post'),
data: $('#blogform').serialize() + "&post_content=" + $post_content + "&time=" + $time,
type: "POST",
dataType: 'json',
encode: true,
success: function(data){
if(!data.success) {
if(data.errors) {
$('#blog-message').html(data.errors).addClass('alert alert-danger');
}
} else {
alert(data.message);
}
}
});
});
Input FileName Checked: I already checked the input name and it's the same.
Image Size: I checked for some related question of mine which is undefined index on file validation and they said image size must be big but I use a small size image sample.
I used Krajee's File Input Plugin.
When I submit this form all things are well n good but I want the controller function not shows in url. I want all things are done in same page. Still the url show
localhost/Naveen/CodeIgniter/welcome/insertform
but I don't want the form_open('') show's in url so how it is possible?
controller welcome.php
public function insertform()
{
if (isset($_POST['mysmt']))
{
$this->form_validation->set_rules('fname', 'Name', 'required');
$this->form_validation->set_rules('femail', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('fmobile', 'Mobile', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('welcome_view');
}
else
{
$_POST['fname'];
$_POST['femail'];
$_POST['fmobile'];
if($this->test_model->insert('user_accounts',array('',$_POST['fname'],$_POST['femail'],$_POST['fmobile'])))
{
$success['success']="Thanks For Join Us";
$this->load->view('welcome_view',$success);
}
}
}
else
{
$this->load->view('welcome_view');
}
}
view welcome_view.php
<?php echo form_open('welcome/insertform'); // ?>
<div class="form-group">
<?php
if(isset($success))
{?>
<input type="button" class="form-control btn-success" value="<?php echo $success; ?>">
<?php }
else
{
echo "";
}?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Name <?php echo form_error('fname'); ?></label>
<?php
$entername = array(
'name' => 'fname',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Name',
'class' => 'form-control',
);
echo form_input($entername); ?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Email <?php echo form_error('femail'); ?></label>
<?php
$enteremail = array(
'name' => 'femail',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Email',
'class' => 'form-control',
);
echo form_input($enteremail); ?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Mobile <?php echo form_error('fmobile'); ?></label>
<?php
$entermobile = array(
'name' => 'fmobile',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Mobile',
'class' => 'form-control',
);
echo form_input($entermobile); ?>
</div>
<div class="form-group">
<?php
$f_formsmt = array(
'name' => 'mysmt',
'value' => 'Submit Form',
'class' => 'form-control btn btn-success',
);
echo form_submit($f_formsmt); ?>
</div>
<?php echo form_close(); ?>
You handle it through applications/config/routes.php
consider you url: localhost/Naveen/CodeIgniter/welcome/insertform
$route['add'] = 'welcome/insertform';
now you can use localhost/Naveen/CodeIgniter/add
You can change whatever the string you want for any controller/function using routes.
Hope you understood :)
You need to add the url in route and add link to your link href
In route.php add:
$route['custom_url'] = 'controller/method';
I used Header("location:../{whatever-filename}")
Then gave that "whatever-filename" the proper routing in the config/routes.php.
Routing without using the redirect function would load the appropriate page but the url would still show the controller and method you're using.
Hope it helps
First of all sorry for the long post with code, but i feel like i need to explain myself straight. The issue is, i'm trying to insert some data into a database and also the file name in the RESTAURANT_IMAGE column. Everything inserts perfectly fine but the image doesn't upload and the file name is not inserted into the database.
EDIT: Edited the callback function to properly return True or False and now i do the insert in the main function if the callback returns true.
Now i am able to upload the image successfully but still dont get the file name and extension to put into my database.
function restaurant_add()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$config = array(
array(
'field' => 'RestaurantName',
'label' => 'Restaurant Name',
'rules' => 'required|callback_restaurant_check'
),
array(
'field' => 'RestaurantAddress',
'label' => 'Address',
'rules' => 'required'
),
array(
'field' => 'RestaurantReservations',
'label' => 'Reservations',
'rules' => 'max_length[1]|integer'
),
array(
'field' => 'RestaurantWifi',
'label' => 'RestaurantWifi',
'rules' => 'max_length[1]|integer'
),
array(
'field' => 'RestaurantDelivery',
'label' => 'Restaurant Delivery',
'rules' => 'max_length[1]|integer'
),
array(
'field' => 'RestaurantMultibanco',
'label' => 'RestaurantMultibanco',
'rules' => 'max_length[1]|integer'
),
array(
'field' => 'RestaurantImage',
'label' => 'RestaurantImage',
'rules' => ''
)
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('sample_navbar_view');
$this->load->view('restaurant_add');
return FALSE;
}
else
{
$file_name = $this->do_upload();
$data = array(
'RESTAURANT_NAME' => $this->input->post('RestaurantName'),
'RESTAURANT_ADDRESS' => $this->input-> post('RestaurantAddress'),
'RESTAURANT_RESERVATIONS'=> $this->input-> post('RestaurantReservations'),
'RESTAURANT_WIFI'=> $this->input-> post('RestaurantWifi'),
'RESTAURANT_DELIVERY'=> $this->input-> post('RestaurantDelivery'),
'RESTAURANT_MULTIBANCO'=> $this->input-> post('RestaurantMultibanco'),
'RESTAURANT_OUTDOOR_SEATING'=> $this->input-> post('RestaurantOutdoorSeating'),
'RESTAURANT_IMAGE'=> $file_name
);
$this->load->model('restaurant_model');
$this->restaurant_model->restaurant_add($data);
return TRUE;
}
}
Callback function to check if the restaurant name exists, if it does, it doesn't register it, if it doesn't sends the data into the model.
function restaurant_check($restaurantname){
$this->load->model('restaurant_model');
$result = $this->restaurant_model->check_restaurant_name($restaurantname);
if($result > 0) {
return FALSE;
}
else {
return TRUE;
}
}
I used the upload file article present in the Codeigniter Documentation.
View Code:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<?php echo form_open_multipart('restaurant/restaurant_add');?>
<form name="restaurant_add" method="post" action="<?php echo site_url().'Restaurant/restaurant_add'; ?>">
<h2>Register your Restaurant</h2>
<input class="form-control" type="text" class="user" name="RestaurantName" placeholder="Restaurant Name">
<input class="form-control"type="text" class="pass" name="RestaurantAddress" placeholder="Restaurant Address">
<input class="form-control"type="number" class="numero" name="RestaurantReservations" placeholder="Restaurant Rerservations">
<input class="form-control"type="number" class="numero" name="RestaurantWifi" placeholder="Wi-Fi">
<input class="form-control"type="number" class="numero" name="RestaurantDelivery" placeholder="Home Deliveries">
<input class="form-control"type="number" class="numero" name="RestaurantMultibanco" placeholder="Have Multibanco?">
<input class="form-control"type="number" class="numero" name="RestaurantOutdoorSeating" placeholder="Esplanada">
<input class="form-control"type="file" class="image" name="RestaurantImage" placeholder="Upload a Picture">
<div class="container">
<?php echo validation_errors(); ?>
</div>
<button class="btn btn-danger"type="submit">Registar</button>
</form>
</div>
</div>
EDIT: Model Code:
function restaurant_add($info)
{
$query =
"INSERT INTO RESTAURANTS
(RESTAURANT_NAME,RESTAURANT_ADDRESS,RESTAURANT_RESERVATIONS,
RESTAURANT_WIFI,RESTAURANT_DELIVERY,RESTAURANT_MULTIBANCO,
RESTAURANT_OUTDOOR_SEATING,RESTAURANT_IMAGE
)
VALUES
(
'".$info['RESTAURANT_NAME']."',
'".$info['RESTAURANT_ADDRESS']."',
'".$info['RESTAURANT_RESERVATIONS']."',
'".$info['RESTAURANT_WIFI']."',
'".$info['RESTAURANT_DELIVERY']."',
'".$info['RESTAURANT_MULTIBANCO']."',
'".$info['RESTAURANT_OUTDOOR_SEATING']."',
'".$info['RESTAURANT_IMAGE']."'
)
";
$result = $this->db->query($query);
return TRUE;
}
function check_restaurant_name($restaurantname) {
$this->db->trans_begin();
$query = "SELECT RESTAURANT_NAME FROM RESTAURANTS WHERE RESTAURANT_NAME = '".$restaurantname."'";
$result = $this->db->query($query);
$rows = $result->num_rows();
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
return $rows;
}
do_upload() function:
public function do_upload()
{
$config['upload_path'] = './assets/images/restaurantes';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('success_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
$upload_data = $this->upload->data();
//Returns array of containing all of the data related to the file you uploaded.
$file_name = $this->upload->file_name;
return $file_name;
}
Here is my controller code:
public function register()
{
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('register_model');
$this->load->library('form_validation');
$this->load->view('head');
$this->load->view('register');
$this->load->view('footer');
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|min_length[5]|max_length[12]|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|matches[passconf]|md5'
),
array(
'field' => 'passconf',
'label' => 'Password Confirmation',
'rules' => 'trim|required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email'
)
);
$this->form_validation->set_message('required', 'Field required');
$this->form_validation->set_rules($config);
if ($this->form_validation->run() === FALSE)
{
$this->load->view('head');
$this->load->view('register');
$this->load->view('footer');
}
else
{
$this->register_model->set_user();
redirect ('login', 'refresh');
}
}
Here is my view code:
<div id="regform" class="one-third column">
<h2>Register</h2>
<?php echo validation_errors();
echo form_open('register'); ?>
<label for="username">Username</label>
<?php echo form_error('username'); ?>
<input type="text" name="username" value"<?php echo set_value('username'); ?>"/>
<label for="password">Password</label>
<input type="password" name="password" value"<?php echo set_value('password'); ?>"/>
<label for="passconf">Password Confirmation</label>
<input type="password" name="passconf" value"<?php echo set_value('passconf'); ?>" />
<label for="email">Email</label>
<?php echo form_error('email'); ?>
<input type="text" name="email" value"<?php echo set_value('email'); ?>"/></br>
<input type="submit" name="submit" value="Register" />
</form>
</div>
The form rules apply, however when i do something wrong, not one of the error messages show up. Any thoughts? I have looked at all other questions but none have an answer to mine. Thanks
The problem is that, in your Controller, you've loaded your View before you've set up the validation.
public function register()
{
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('register_model');
$this->load->library('form_validation');
$this->load->view('head'); // <- too early
$this->load->view('register'); // <- too early
$this->load->view('footer'); // <- too early
// nothing below here is going to work because you've already loaded the page
....
You'll need to rework your Controller so that loading your View is always done last for every condition.
All I want to do is make a form, in Zend Framework, that looks like this:
<p id="foo">
<form action="#" method="post">
<label>Start:</label>
<input id="start" type="text" name="start" />
<label>End:</label>
<input id="end" type="text" name="end" />
<input type="submit" name="submit" value="Submit" />
</form>
</p>
and I simply cannot do it. :( I can stick in in the view like that but then I don't get validation and filtering.
Any tips on how to figure out decorators and Zend_Form?
This works. I've adapted this from a form I'm using so I stuck in a few other things like ID's that you can use if you like. Useful to see how it all comes together anyway:
In my controller:
private function _theForm() {
$form = new Zend_Form;
$form->setAction('/controller/action')
->setMethod('post')
->addAttribs(array('id' => 'an_id_for_the_form'));
$form->addElement('text', 'start', array(
'validators' => array(
'NotEmpty'
),
'label' => 'Start:',
'id' => 'someid',
'required' => true,
'decorators' => array(
'ViewHelper',
'Errors',
'Label',
),
));
$form->addElement('text', 'end', array(
'validators' => array(
'NotEmpty'
),
'label' => 'End:',
'id' => 'someotherid_if_you_like',
'required' => true,
'decorators' => array(
'ViewHelper',
'Errors',
'Label',
),
));
$form->addElement('submit', 'submitSomething', array(
'label' => 'Submit',
'decorators' => array(
'ViewHelper',
)
));
$form->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'p', 'id' => 'foo')),
'Form',
));
return $form;
}
I then call that elsewhere in my controller, like:
$form = $this->_theForm();
$this->view->form = $form;
Then you can use it in your view like:
<?php echo $this->form; ?>
If you are comfortable working with views but also needs the validation and filter features, you can still use Zend Form.
class Default_Form_Search extends Zend_Form
{
public function init()
{
$start = new Zend_Form_Element_Text('start');
$start->setRequired(true)
->addValidator('Date', false, array('format' => 'YYYY-MM-dd'))
->setDecorators(array(
array('ViewHelper')
));
$this->addElement($start);
// For end
}
}
In your controller:
$form = new Default_Form_Search;
$form->setAction('/search');
if ($this->getRequest()->isPost())
{
if ($form->isValid($this->getRequest()->getPost())
{
// Search here
}
{
var_dump($form->getMessages();
}
}
$this->view->form = $form;
Then in your view, you simply form the HTML as is but output the element like this:
<p id="foo">
<form action="<?php echo $this->form->getAction() ?>" method="post">
<label>Start:</label>
<?php echo $this->form->start ?>
<label>End:</label>
<?php echo $this->form->end ?>
<input type="submit" name="submit" value="Submit" />
</form>
</p>
Here is an example of how I create a Zend form:
class Mobile_Form_Login extends Zend_Form
{
public function init()
{
$this->setName('authenticate');
$nick = $this->createElement('text', 'nick');
$nick->setRequired(true);
$nick->addValidators(array(
new Zend_Validate_StringLength(3, 10),
));
$pass = $this->createElement('password', 'password');
$pass->setAttrib('size', 10);
$pass->setRequired(true);
$pass->addValidators(array(
new Zend_Validate_StringLength(6, 128),
));
$this->addElements(array($nick, $pass));
}
}
The later, in my controller
$form = new Mobile_Form_Login();
if (!$form->isValid($_POST)) {
// handle errors
}
// else render()