Hi i have a problem with form validation on this function it run false at PAGELOAD what did i do wrong?
i use stencil template
install codeiginiter in sub-folder after wordpress website
public function create() {
$this->stencil->title('Tour');
$this->stencil->layout('booktour_layout');
$this->stencil->css('font-awesome');
$this->stencil->paint('booktour_create');
$this->load->helper('form');
$this->load->library('form_validation');
if($this->form_validation->run() === FALSE)
{
echo "<script>alert('error');</script>";
}
else
{
echo "<script>alert('success');</script>";
}
}
When i load the page it echo script at pageload not the submit form
Any though? Thank you
put your code in isset function that mean it will not work without submit form.
please change the index with any of our input name
if(isset($_POST['index'])) {
if($this->form_validation->run() === FALSE)
{
echo "<script>alert('error');</script>";
}
else
{
echo "<script>alert('success');</script>";
}
}
First check whether the POST is requested by using if(isset($_POST)){<Your Validation Code;>} OR if(!empty($this->input->post())){<Your Validation Code;>}
Hope this will help you in solving your problem
As I remember, default result for validation is false. And only when values pass thru rules it sets to true. So while there is no rules, you will receive false.
Let me explain more. Write a controller:
$this->load->library('form_validation');
if($this->form_validation->run() === FALSE) { echo "<script>alert('error');</script>"; }
else { echo "<script>alert('success');</script>"; }
and call it without query. You will receive error. It means that you shoud check that query is present and add at least one rule before calling validation
Related
I have an observer action setup, that checks if a product page is loaded. If so, it calls a custom help that deals with all of the GET paremeters. It used to work for over 4 years and have suddenly stopped (the only thing that changed on the 3rd party's side is the naming of those parameters).
Here is the observer action:
public function productView($observer) {
/*#var $block Mage_Core_Block_Abstract*/
$block = $observer->getEvent()->getBlock();
if ($block && $this->getProduct()){
if ($block->getModuleName() == 'Mage_Catalog'){
$productId = $this->getProduct()->getEntityId();
//If params exist - save
if ($this->ParamsHelper()->saveParams($productId)){
//code omitted
}
}
}
}
Here is the helper's action:
public function saveParams($productId) {
if (is_numeric($productId)){
$params = Mage::app()->getRequest()->getParams();
if (!empty($params['image']) && !empty($params['config'])){
//never gets here
return true;
}
}
return false;
}
If I try to var_dump the $params, I get the following array which only includes product_id:
array(1) { ["id"]=> string(3) "664" }
Expected result is to be able to access all the GET parameters passed via url in product view.
Any help or guidance is much appreciated.
EDIT
Product URLs are similar to product names, like f.e.:
domain.com/red-jacket
In a perfect case, I would expect to get parameters passed like following:
domain.com/red-jacket?param1=aaa¶m2=bbb
Not sure whats the exact problem is ... but for domain.com/red-jacket?param1=aaa¶m2=bbb you can get parameters in this way:
$params = Mage::app()->getRequest()->getParams();
$param1 = $params['param1']
or
$param1 = Mage::app()->getRequest()->getParam('param1');
//code for get parameters in view page.
$arrParams = Mage::app()->getRequest()->getParams();
echo "Get Parameter"; echo '<pre>', print_r($arrParams);
Codeigniter: Why is my database function call no longer parsed in further controllers that I am creating even though I have done a similar query in previous controllers; and they are working just fine? Using output->profiler(), I found out that the database function call in the create_student() function is not parsed. What is strange to me is why the same function structure worked in previous controllers I had created.The following code tag works fine in other controllers using related method name like public function create_group(), public function create_class(). The same pattern is repeated.
public function create_student(){
$this->output->enable_profiler(TRUE);
if($this->input->is_ajax_request() && $this->input->post('ajax') == 1){
$this->form_validation->set_rules('first_name[]', 'First Name', 'trim|required|min_length[2]|max_length[20]');
$this->form_validation->set_rules('last_name[]', 'Last Name', 'trim|required|min_length[2]|max_length[20]');
if ($this->form_validation->run() == FALSE) {
$this->output->set_status_header('400');
echo '<span class="admin_validation_error" style="color:#ff0000">'.validation_errors().'</span>';
} else {
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
if($this->student_model->create_student($first_name, $last_name) == true){
echo '<span class="validation_success" style="color:green; font-weight:bolder">Well done! Student(s) successfully created.</span>';
}
}
}else{
redirect('errors/not_found');
}
}
I finally found what was wrong. It's funny though. I failed to include the username field in the subsequent tables I was creating. This had made it impossible for me to execute queries or load Datatable. The username field is present in the former tables I had created and needs to be in all the tables I am yet to create for the application. Thanks guys for giving me a clue. Cheers
I have set up my routes.php to suit the nature of my site. Unfortunately, there is a problem with my last route i.e.:
$route['(:any)'] = "profile/profile_guest/$1";
If the username password name passed is correct, for e.g. domain.com/username, it will load his/her data. if not, it loads the page with errors (because failure to retrieve data with non-existent user in database). This is my problem! I want to avoid this error showing.
Is there anyway I could avoid this error from happening? None of the echoes seems to be printing or the redirect neither is working. Don't know why! it is as if the code inside this method is not executing and the view is loaded instead. below is part of the profile_guest function:
public function profile_guest($username)
{
$username = $this->uri->segment(1);
//echo "Hello " . $username;
redirect('main', 'refresh');
if($username != '')
{
/* echo "<h1>HELLO WORLD SOMETHING</h1>"; */
It's hard to say without seeing the rest of the code.
Maybe you need to check the value before running the query:
// user_model
function get_user($username = NULL){
if($username){
return $this->db->query(...
}else{
return false;
}
}
Then check that the query returned anything before loading the view
if($this->user_model->get_user($username){
//show the page
}else{
echo "no user found";
}
One of my forms uses AJAX to send data. Since my page never reloads because of AJAX, is there a way I can still make use of form_validation to validate and output which fields are wrong? The url my form sends to using jquery is contact/ajax_send.
The entire AJAX works fine except I haven't inserted any validation yet.
Since you are using ajax to send the data, what you can do is, simply add the form_validation code calls before inserting into the database.
If there are any validation errors, you can either return the error messages as json response to the front end to display the error messages.
The form validation library assigns all errors that occurred to a private array called _error_array, but does not expose it or provide documentation on it (notice the first underscore?). Just return a json encoded object of the errors in the controller:
echo json_encode($this->form_validation->_error_array);
If you wish, you can extend CodeIgniter's form validation library, perhaps returning FALSE instead of an empty array... or whatever you see fit:
/* libraries/MY_Form_validation.php */
<?php
class MY_Form_validation extends CI_Form_validation
{
function __construct($config = array())
{
parent::__construct($config);
}
function error_array()
{
if (count($this->_error_array) === 0) return FALSE;
else return $this->_error_array;
}
}
Now, drop the initial underscore in the controller:
echo json_encode($this->form_validation->error_array);
Then decode and display errors on the client.
I found a method, thanks in part to Jordan's answer. This returns an array containing the names of the fields which have errors.
// library/MY_Form_validation.php
class MY_Form_validation extends CI_Form_validation {
public function get_field_data(){
return count($this->_field_data) ? $this->_field_data : FALSE;
}
}
// Controller file
$field_data = $this->form_validation->get_field_data();
foreach($field_data as $key=>$val){
if($key == '__proto__') break;
foreach($val as $k=>$v){
if($k == 'error' && !empty($v)) $errors[] = $key;
}
}
$return = array('success'=>FALSE, 'errors'=>$errors);
The above code checks the error key whether it's empty or not. Empty values mean that it passed the CI validation while none empty values would contain the string you see when you use validation_errors(). Since I'm after those fields which have errors, I only needed to see which values are not empty disregardig those which are.
I am using the HMVC pattern in CodeIgniter. I have a controller that loads 2 modules via modules::run() function and a parameter is passed to each module.
If either module cannot match the passed paramter I want to call show_404(). It works, but it loads the full HTML of the error page within my existing template so the HTML breaks and looks terrible. I think I want it to redirect to the error page so it doesn't run the 2nd module. Is there some way to do that and not change the URL?
Is it possible to just redirect to show_404() from the module without changing the URL?
Here is an over simplified example of what's going on:
www.example.com/users/profile/usernamehere
The url calls this function in the users controller:
function profile($username)
{
echo modules::run('user/details', $username);
echo modules::run('user/friends', $username);
}
Which run these modules, which find out if user exists or not:
function details($username)
{
$details = lookup_user($username);
if($details == 'User Not Found')
show_404(); // This seems to display within the template when what I want is for it to redirect
else
$this->load->view('details', $details);
}
function friends($username)
{
$details = lookup_user($username);
if($friends == 'User Not Found')
show_404(); // Redundant, I know, just added for this example
else
$this->load->view('friends', $friends);
}
I imagine there is just a better way to go at it, but I am not seeing it. Any ideas?
You could throw an exception if there was an error in a submodule and catch this in your controller where you would do show_404() then.
Controller:
function profile($username)
{
try{
$out = modules::run('user/details', $username);
$out .= modules::run('user/friends', $username);
echo $out;
}
catch(Exception $e){
show_404();
}
}
Submodule:
function details($username)
{
$details = lookup_user($username);
if($details == 'User Not Found')
throw new Exception();
else
// Added third parameter as true to be able to return the data, instead of outputting it directly.
return $this->load->view('details', $details,true);
}
function friends($username)
{
$details = lookup_user($username);
if($friends == 'User Not Found')
throw new Exception();
else
return $this->load->view('friends', $friends,true);
}
You can use this function to redirect 404 not found page.
if ( ! file_exists('application/search/'.$page.'.php')) {
show_404(); // redirect to 404 page
}
its very simple , i solved the problem
please controler name's first letter must be capital e.g
A controller with
pages should be Pages
and also save cotroler file with same name Pages.php not pages.php
also same for model class
enjoy