I'm not a pro, but know my way around PHP, I'm new to Codeigniter.
Been going through these tutorials: http://net.tutsplus.com/articles/news/codeigniter-from-scratch-day-5-crud/
OK, so I have a page that lists users, clicking on users name will go to an edit page, the url of that page being: index.php/users/edit/1 (where 1 is the users id)
On edit page is a form, this form contains a few parts, each part is populated from different tables in the DB. So my Controller for edit is as follows:
function edit() {
//load model
$this->load->model('users_model');
//assign user data from DB
$data['data_user'] = $this->users_model->getUser($this->uri->segment(3));
//get users Password, using username from above
$data['data_user_password']= $this->users_model->getUserPassword($data['data_user'][0]->UserName);
$data['page_content'] = 'pages/users_edit';
$this->load->view('template/template', $data);
}
Notice:
$data['data_user'] contains users data like name, username, email
$data['data_user_password'] contains users password from a different table
I can then populate the form, on users_edit.php, this all works fine.
I'm accessing this data by doing the following:
if (is_array($data_user)) {
foreach($data_user as $user)
{
$userID = $user->id;
$userName = $user->Name;
$userUserName = $user->UserName;
$userMail = $user->Mail;
$userDepartment = $user->Department;
$userWorkPhone = $user->WorkPhone;
$userHomePhone = $user->HomePhone;
$userMobile = $user->Mobile;
}
}
//user password
if (is_array($data_user_password)) {
foreach($data_user_password as $user)
{
$userPassword = $user->value;
}
}
Name:
<?php echo form_input('name', set_value('name', $userName), 'id="name" class="inputLong"'); ?>
When I post, I'm sending data to: index.php/users/update
My controller for this page so far is:
function update() {
echo '<pre>';
print_r($_POST);
echo '</pre>';
//exit();
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('pages/users_edit');
}
else
{
$this->index();
}
}
For now, I'm just testing validation on users "name" where form input=name id=name
I think I'm not handling the if ($this->form_validation->run() == FALSE) part of it correctly, if the form contains data, it passes and redirects to index, if I leave name blank it either not handling the edit page correctly, or I dont know, something isnt right.. I think its because the page is being reloaded using the post array, and not passing the $data like I did in function edit().
Back to the form page, where it should be showing the validation_errors, its showing:
The Name field is required.
This is correct, however, for the rest of the fields that should be pre-populated, its showing PHP error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: userUserName
Filename: pages/users_edit.php
Line Number: 50
You could do your validation inside your edit function instead of having an update function, that way, your data is still available for your view and if the validation has errors, codeigniter will take in charge to repopulate your fields. If the validation is ok, you do your next step
function edit() {
//load model
$this->load->model('users_model');
//assign user data from DB
$data['data_user'] = $this->users_model->getUser($this->uri->segment(3));
//get users Password, using username from above
$data['data_user_password']= $this->users_model->getUserPassword($data['data_user'][0]->UserName);
$data['page_content'] = 'pages/users_edit';
$this->load->view('template/template', $data);
//is the form submitted
if(form submit){
if ($this->form_validation->run() == TRUE)
{
$this->index();
}
else
{
$this->load->view('pages/users_edit', $data);
}
}
}
$this->load->view('pages/users_edit');
Inside your function update(), after your validation you load view but you don't PASS any data variables to it. So you don't have any variables which you can access at your view file..
You have to set your variables the same way as in your function edit():
$this->load->view('template/template', $data);
Currently there is not set variable $data_user so you can't loop it and use it..
Related
I gotta validate the "username" & "password".
This is my table with the users:
And here the users:
The login system must "clasify" those users who are ADMIN users (tipo = 0) and simple users (tipo = 1). Note: ADMIN and simple users have different screens after loging
I gotta validate that the guy who access is an active member (i got problems with it)
ESTATUS = 1 IS AN ACTIVE USER
ESTATUS = 0 IS NOT AN ACTIVE USER
And i do not know how should i validate if a guy did not write anything and he only click on the "login" button (i should not connect to the server to validate it)
Here is my code, it works properly.. It validates if the user is an ADMIN or a simple user and if the information written in the login system corresponds to a person in the database.
But i do not know how should i do the "ESTATUS" validation and how i should check blank fields without connecting to the server :/
<?php
Class Login extends CI_Controller{
public function index(){
$this->load->view('login_form');
}
public function do_login()
{
if(isset($_POST['login'])){
$user=$this->input->post('usuario', true);
$pass=$this->input->post('contrasena', true);
$cek = $this->m_login->proceso_login($user,$pass);
$hasil=count($cek);
if($hasil > 0){
$pelogin =$this->db->get_where('usuarios',array('usuario' => $user, 'contrasena' => $pass))->row();
if($pelogin ->tipo == 0){
redirect('login/admin');
}
else{
redirect('login/usuario');
}
}
redirect('login/index');
}
}
You need to do some validation before inserting your data into the database:
public function do_login()
{
// load the form_validation library
$this->load->library('form_validation');
$this->form_validation->set_rules('Your_username_field_name', 'Username', 'trim|required|min_length[3]|alpha_numeric');
$this->form_validation->set_rules('Your_password_field_name', 'Password', 'trim|required|min_length[6]');
// if there is errors
if ($this->form_validation->run() == FALSE) {
// this will load your form with the errors
$this->load->view('Login_main');
} else {
// if no errors we will hit the database
$user=$this->input->post('usuario', true);
$pass=$this->input->post('contrasena', true);
$cek = $this->m_login->proceso_login($user,$pass);
$hasil=count($cek);
if($hasil > 0){
$pelogin =$this->db->get_where('usuarios',array('usuario' => $user, 'contrasena' => $pass))->row();
if($pelogin ->tipo == 0){
redirect('login/admin');
}
else{
redirect('login/usuario');
}
}
redirect('login/index');
}
}
then in your Login_main view you could add this line of code to echo the errors to see what's going wrong:
<?php echo validation_errors(); ?>
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.
I have a form in laravel.
If submits a bunch of information about the user and then submits it to a store() function.
public function store()
{
$input = Input::except('_token');
if ( ! $this->validator->with($input)->passes())
{
return Redirect::back()->withErrors($this->validator->errors())->withInput($input);
}
$this->title->save($input);
return Redirect::back()->withSuccess( trans('main.created successfully') );
}
public function save()
{
if ($this->query && $this->values)
{
return DB::statement($this->query, array_values($this->values));
}
}
The query is executed in the save() function
The User can then access the info at www.mysite/{$id}
The {$id} variable is generated when the query is executed and saved into my db. It is the value of the id column in my db.
I want to email the user when they submit the form to say that the info has been entered successfully and that they can view it at www.mysite/{$id} but I don't know what variable I should put into my mailer() function to denote the {$id} because that variable is generated when it is saved. How do I implement a way to pass the {$id} variable to my mailer() function?
One other question – in the user controller login method, after checking pressed button (login or forget password), in line : $data = $this->user_model->login(); return correct user information; "user name, family, user id" to be used in dashboard for using in log table and heAder of pages how to send this data to dashboard?
i tried to send it via redirect() but it fail
if ($this->form_validation->run() == TRUE) {
if (!empty($_POST['login'])) {
$data = $this->user_model->login();
if ($data != NULL)
{
redirect('dashboard');
} else {
redirect('user/login', 'refresh');
}
} elseif (!empty($_POST['forget'])) {
redirect('user/recover');
}
}
$this->data['subview'] = 'users/login';
$this->load->view('users/_layout_modal', $this->data);
Function redirect() doesn't save anything. You can try save $data to session by writing $this->session->set_userdata('some_name', $data);
Then you can call them with $this->session->userdata('some_name');
Note that $data can be object or array.
Assume that $data is array, then in dashboard you can use something like this:
$data = $this->session->userdata('some_name');
echo 'Username: '.$data['username'].'<br />';
echo 'Family: '.$data['family'];
...... so on ........
As per your question, you are validating the user login details and creating session for them.
Then store user information in session.
set session library auto-load in config/autoload.php. Then create session as below.
$this->session->set_userdata(
array(
"username"=>$username,
"user_id" => $user_id,
"family" => $family
)
);
In Dashboard:
You can access session with it's name:
echo $this->session->userdata("username");
i created a update profile page.
i have this in the controller to populate the form and also handle update:
$user = User::model()->findByPk(Yii::app()->user->id);
// Collect user input
if (isset($_POST['User'])) {
$user->attributes = $_POST['User'];
if ($user->save()) {
echo "update successfully";
}
else {
echo "update failed";
}
}
// View
$this->render('user_view', array('user'=>$user,));
however, this doesn't work. although $user->save is true, the record is not updated in the database. i've also check that $_POST['User'] is returning the updated data but $user->attributes is not saving them.
why is that so?
You need to set which model attributes are "safe" for "massive assignments". Read more about this here.
The mass attribute assignment $user->attributes will only assign to variables with validation rules. Just give the name attribute a rule, even if it's just the "safe" validator.
public function rules()
{
return array(
array('name', 'safe')
);
}
I'm pretty sure this is the problem you are having, it's happened to me!