I am pretty knew to code igniter / OOP but I am giving it a shot and a little stumped at this point.
I have 2 functions. One is the search which loads data from a model. The other is the save function.
My issue is, when running save() I am getting errors because its trying ti display the validation errors but we no longer have the data from the database that we got from the search() function.
I feel that it would be redundant to include all the details form the search back into this save function which is why I think I am doing something wrong.
public function search()
{
// Define some vars
$data['title'] = 'Submit Attrition';
$data['js_file'] = 'submit.js';
// Load our helper
$this->load->helper('form');
// Get the user and pass it to the model
$empQID = $this->input->post('empQID');
$data['userDetails'] = $this->submit_model->get_details($empQID);
$data['languages'] = $this->submit_model->get_languages();
$data['types'] = $this->submit_model->get_types();
$data['ratings'] = $this->submit_model->get_ratings();
$data['processes'] = $this->submit_model->get_processes();
// Send the data to the views
$this->load->view('templates/header', $data);
$this->load->view('submit/search', $data);
$this->load->view('templates/footer', $data);
}
/**
* Validate & save attrition submission
*
* #author Carl
* #return void
*/
public function save()
{
$data['title'] = 'Submit Attrition';
$this->load->library('form_validation');
$this->form_validation->set_rules('language', 'Supporting Language', 'required');
// Validation failed, show form w/ validation errors
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('submit/search', $data);
$this->load->view('templates/footer', $data);
}
else
{
// Success : Send data to model
$this->submit_model->save_attrition();
$this->load->view('templates/header', $data);
$this->load->view('submit/success', $data);
$this->load->view('templates/footer', $data);
}
}
I'm not sure I entirely understand your question, but I think I understand what you're trying to do. In CodeIgniter, you do something like this:
class MyController
{
// this controller action will load whether the form is submitted or not
// $user_id is set by the router
public function save($username)
{
// if the users not in the database, throw a 404 error
$user = $this->db->get_where('users', ['username' => $username]);
if(!$user) {
return show_404();
}
// if it's not a post request, then the form hasn't been submitted
// so don't bother validating it
if($router->fetch_method() === 'POST' && $form_validation->run() === TRUE)
{
$user['name'] = $this->input->post('name');
$this->db->update('users', $user);
$this->load->view('success_page');
// return so we don't render the form again
return;
}
// this will happen in all cases, __except__ when the form was submitted
// with valid data
$this->load->view('form');
}
}
I've skipped on details for brevity (like loading the relevant libraries), and because I can't remember all the CI syntax.
Related
I have the following method in my controller:
(shortened version but all the key pieces are here...)
class Widget extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('widget_model');
$this->load->helper('form');
$this->load->library('form_validation');
}
public function assign()
{
//logic to display form.
if ($this->input->method() == "get" ) {
$data['save_status'] = '';
$data['title'] = 'Assign Widget';
$data['main_content'] = "assign";
$this->load->view('includes/template',$data);
}
else
{
//logic to handle POST
...
$data['save_status'] = 'Sucessfully saved to db';
$data['title'] = 'Assign Widget';
$data['main_content'] = "assign";
$this->load->view('includes/template',$data);
}
}
Everything works, except I don't know what the proper way to clear the form data is... because when I press F5 thinking I'm refreshing my page, it's actually resubmitting the data to the database.
Sorry, i'm sure this is a noob question.
Thanks.
EDIT 1
for now, I added a redirect at the end of post logic like this;
redirect(base_url()."index.php/thesamecontroller/thesamemethod");
and that takes the user to the same page, but without the form data being available.
Is this the best way to handle it?
I'm developing a function that should enable users to update their personal information and I'm using CI form validation library. I'd want to know if what I'm doing is right.
public function updateDetails()
{
$this->load->model('users_model'); // load users model
$username = $this->input->post("username", true); // get the post from view
$this->form_validation->set_rules('username', 'Username', 'required|max_length[32]');
if($this->form_validation->run() === true)
{
// Send to model
}
}
Is this right? Or is there another method to do this?
yes so far you're right
but you should process if the validation is successful
public function updateDetails()
{
// load the library if not already loaded in config/autoload.php
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|max_length[32]');
if($this->form_validation->run() === true)
{
$this->load->model('users_model'); // load users model
$username = $this->input->post("username", true); // get the post from view
// Send to model
}
else
{
$data['error_message'] = "form not valid ...blablabla";
//go back to form
$this->load->view("form_vew",$data);
}
}
This doesn't make sense to me with how MVC works in codeigniter.
I have a 'controller/Company.php' loads using example.com/company/
function index() {
$page = uri_string();
$data['title'] = ucfirst($page);
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view($page, $data);
$this->load->view('templates/footer', $data);
}
This loads 'views/company.php' and displays form:
<h1 class="page-title"><?php echo $title; ?></h1>
<?php echo form_open('company/update', 'class="form-horizontal" role="form"'); ?>
<input name="company_name" type="text">
<?php echo form_error('company_name'); ?> //if empty display error
//rest of form and submit button
I then have an update function inside the Company controller:
function update() {
$this->form_validation->set_rules('company_name', 'Company Name', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('company');
} else {
//update db, load model, post data, success, etc
}
}
My issues are:
If I just load the form view again then I lose my header, nav, footer, etc.
If I redeclare all 4 of those views, I lose the original data variables: $title, $page
If I use redirect('company'); to load the controller again then I would lose the submitted data and the form_error('company_name'); would be empty
I hope I'm missing something big because I have been staring at this all day and search for answers but can't find a tutorial of how all of this is suppose to work in the "real world" Thanks
Yes of course. Controller method act as single function in your project.
if i explain it more
<?php
public function one()
{
echo '1';
}
public function two()
{
echo '2';
}
In here function one don't know what is function two. So both functions are acting as Independent.
According to your question
you load this views in index()
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view($page, $data);
$this->load->view('templates/footer', $data);
but in update() you load only
$this->load->view('company');
so in second function there are no header, navigation, and footer.
Answer for your Question is
<?php
if ($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view('company');
$this->load->view('templates/footer', $data);
} else
{
//update db, load model, post data, success, etc
}
For question Two
you can use like this
<?php
if ($this->form_validation->run() == FALSE)
{
$page = uri_string();
$data['title'] = ucfirst($page);
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view('company');
$this->load->view('templates/footer', $data);
} else
{
//update db, load model, post data, success, etc
}
I have a weird bug.
Form validation is doing both TRUE and FALSE actions.
For TRUE, the database model (scrape_url_model) runs so the database is updated, but then the views are run as though form validation is FALSE.
The FALSE view (scrape_url/index) is shown instead of the view associated with a successful validation (scrape_url/form_success).
I'm getting the validation error message The URL is already in the database from the callback function.
public function index(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('', '');
$data['pageTitle'] = 'URL Scraping Tool';
$this->form_validation->set_rules('event_url', 'URL', 'trim|required|callback_url_check');
if ($this->form_validation->run() == FALSE){
$this->load->view('templates/header', $data);
$this->load->view('scrape_url/index', $data);
$this->load->view('templates/footer');
}
else {
$this->load->library('Db_queries');
$this->load->library('session');
$this->load->helper('url');
list($session_data['alert'],
$session_data['alert_type'],
$session_data['countUncategorizedDecks'],
$session_data['event_id'],
$session_data['eventDate']) = $this->scrape_url_model->insert_decks_and_cards();
if ($this->input->post('last_url') == 'yes'){
$this->scrape_url_model->insert_md_percentage($session_data['eventDate']);
}
$this->session->set_userdata($session_data);
$this->load->view('templates/header', $data);
$this->load->view('scrape_url/form_success', $data);
$this->load->view('templates/footer_ajax');
}
}
public function url_check($event_url) {
$url_regex = "/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
if (preg_match($url_regex, $event_url) == FALSE) {
// check to see if input is a URL
$this->form_validation->set_message('url_check', 'Please enter a URL including "http://".');
return FALSE;
}
$this->load->database();
$sql = 'SELECT url FROM event';
$s = $this->db->conn_id->query($sql);
$used_urls = $s->fetchAll(PDO::FETCH_COLUMN, 0);
if (in_array($event_url, $used_urls)){
$this->form_validation->set_message('url_check', 'The URL is already in the database.');
return FALSE;
}
return TRUE;
}
Try using statement:
$this->form_validation->run() == true
and then code your conditions accordingly. It will work and will also easy to understand.
I am at the tail end of signing in a created user to an account. I've commented out my flow and everything seems to make since, however I am missing a step or two because now the post data password is not being hashed.
CONTROLLER:
function validate_credentials()
{
// WHEN THE VIEW IS LOADED THIS FUNCTION IS CALLED AND LOADS MODEL AS WELL AS DEFINES THE SALT VARIABLE AND LOADS THE ENCRYPTING HELPER LIBRARY
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
$salt = $this->_salt();
$this->load->library('encrypt');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->encrypt->sha1($user->salt. $this->encrypt->sha1($this->input->post('password')))
);
$user = $this->um->validate($data);
}
// IF ITS A REAL USER OPEN THE GATE AND LET THEM IN
if($user)
{
$this->session->set_userdata($data);
redirect('account/dashboard');
}
else
{
$this->index();
}
}
MODEL:
function validate($data)
{
$this->output->enable_profiler(TRUE);
// TAKING THE DATA FROM THE MODEL AND CHECKING IT AGAINST THE STORED INFO IN THE DB
$query = $this->db->where($data)->get('users', 1);
if($query->row())
{
return $query->row();
}
}
thanks in advance
$user->salt should just be $salt.