codeigniter views with dynamic parameters - codeigniter

I have a edit view whose url is /group/edit/1 where 1 is the group id which is dynamic.
I am validating the form data in controller as :
if ($this->form_validation->run() == FALSE)
{
$this->load->view('group/edit', $data);
}
How do I pass the id parameter "1" to this view ?
Below option does not work since the url has to be group/edit/1
$this->load->view('edit', $data);

You're thinking about this wrong. You want to have a view called edit.php and pass the number 1 into it, or perhaps more to the point, you want to get the data for 1 from your model and pass the return value of your model into your view. Consider this:
controller
function edit($id)
{
$data['item_info'] = $this->whateverModel->getItem($id);
$this->load->view('edit', $data);
}
Then in your edit view, you can refer to the data like this:
view
echo $item_info['id'];
echo $item_info['name']; //or whatever you pass back from the model

Is this what you mean?
$this->load->view('group/edit/'.$parameter, $data);
That would make it load your 1, as you are simply defining the path of the VIEW document
Per CodeIgniters reference this is the format:
$this->load->view('folder_name/file_name');
http://codeigniter.com/user_guide/general/views.html
Not sure if you are confused by routing vs views, here is a quick difference:
If you want http://www.example/group/edit/10
then you need a route setup, not a view.
If you want http://www.example/ and to display the contents from page main.php (in your views folder) then you do $this->load->view('main'); inside your primary controller.

This is what I am doing. Is this acceptable ?
Controller action :
function edit($id)
{
$group_q = $this->db->query("SELECT * FROM groups WHERE id = ?", array($id));
$group_data = $group_q->row();
/* Form fields */
$data['name'] = array(
'name' => 'name',
'id' => 'name',
'value' => $group_data->name,
);
$options = array("A", "B", "C", "D");
$data['group_parent'] = $options;
$data['group_parent_status'] = $group_data->parent_id;
$data['group_id'] = $id;
/* Form validations */
$this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[2]');
if ($this->form_validation->run() == FALSE)
{
if ($this->input->post('submit', TRUE))
{
$data['name']['value'] = $this->input->post('name', TRUE);
$data['group_parent_status'] = $this->input->post('group_parent', TRUE);
}
$this->load->view('group/edit', $data);
}
else
{
$data_name = $this->input->post('name', TRUE);
$data_parent_id = $this->input->post('group_parent', TRUE);
$data_id = $id;
if ( ! $this->db->query("UPDATE groups SET name = ?, parent_id = ? WHERE id = ?", array($data_name, $data_parent_id, $data_id)))
{
$this->session->set_flashdata('error', "Error");
$this->load->view('group/edit', $data);
} else {
$this->session->set_flashdata('message', "Success");
redirect('account');
}
}
return;
}
View file :
<?php
echo form_open('group/edit/' . $group_id); /***** NOTE THIS STEP *****/
echo "<p>";
echo form_label('Name', 'name');
echo "<br />";
echo form_input($name);
echo "</p>";
echo "<p>";
echo form_label('Parentp', 'group_parent');
echo "<br />";
echo form_dropdown('group_parent', $group_parent_active);
echo "</p>";
echo form_hidden('group_id', $group_id);
echo form_submit('submit', 'Submit');
echo form_close();
?>

Related

Codeigniter User's Data

Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = 'Login';
$this->form_validation-> set_rules('username', 'Username', 'required');
$this->form_validation-> set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$this->db->select("*");
$this->db->from("user");
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->result();
}
else {
return false;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}

how to get data from database throught model using codeigniter with for each loop

http error occured while calling data from model using function
model
public function getProductCombo() {
$q = $this->db->get_where('products', array('type' => 'combo'));
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
controller
function sets() {
$this->sma->checkPermissions();
$this->load->helper('security');
$this->data['error'] = (validation_errors() ? validation_errors() :
$this->session->flashdata('error'));
// problem in this line also
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
$bc = array(array('link' => base_url(),
'page' => lang('home')),
array('link' => site_url('sales'),
'page' => lang('products')),
array('link' => '#', 'page' => "sets")
);
$meta = array('page_title' => "Add Sets", 'bc' => $bc);
$this->page_construct('sales/sets', $meta, $this->data);
}
First of all, No need to include the curly braces for $q->result
foreach ($q->result as $row)
{
$data[] = $row;
}
No need to use validation_errors in your php file.You can directly load your form page.Use validation_errors() in view page.
In your Controller, do this
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
Then in your formpage you can echo
<?php echo validation_errors(); ?>
change this line to
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
this
$this->data['showcombo'] = $this->load->sales_model->getProductCombo();
Because your
model name is
public function getProductCombo()
{
}
Firstly you load model in controller. And then called function, which you have defined in model..
$this->load->model('sales_model','sales'); // sales is alias name of model name
$this->data['showcombo'] = $this->sales->getComboProduct();

codeigniter how to show data in functions

My model:
function get_data($id)
{
$this->db->select('id, Company, JobTitle');
$this->db->from('client_list');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
I want to get the the data from get_data(), is this the right way?
public function show_data( $id )
{
$data = $this->get_data($id);
echo '<tr>';
echo '<td>'.$data['Company'].'</td>';
echo '<td>'.$data['JobTitle'].'</td>';
echo '<td>'.$data['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
Use the row_array() function to get the data in the array format.
Reference url
http://ellislab.com/codeigniter/user-guide/database/results.html
you can use foreach loop to print
foreach ($data->result() as $row)
{
echo '<tr>';
echo '<td>'.$row['Company'].'</td>';
echo '<td>'.$row['JobTitle'].'</td>';
echo '<td>'.$row['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
thank you
just to improve answer, I use "general_model" for all my controllers, there are some exceptions where I need special queries, I just create desired model so "general_model" stays same and I can use it in any project.
e.g.
general_model.php
function _getWhere($table = 'table', $select = 'id, name', $where = array()) {
$this->db->select($select);
$q = $this->db->get_where('`'.$table.'`', $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
.
.
.
//bunch of another functions
in controller I just call
$this->data['books'] = $this->general_model->_getWhere('book', '*', array('active' => '1'));
$this->render('book_list_view'); // $this->load->view('book_list_view', $this->data);
sidenote: I am extending CI_Controller therefore I use $this->data['books'] instead $data['books'] to pass data into view
in view
//check if there are any data
if ($books === FALSE) {
//some error that there are no books yet
} else {
//load data to table or something
foreach ($books as $book) {
$book->id; // book id
}
}

How to show validation errors using redirect in codeigniter?

I have been dealing with a problem for a while. How can I set the validation errors using redirect in a function? This is the code I have in my controller :
function send()
{
$this->form_validation->set_rules('e-mail', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('cellphone', 'Cellphone Number', 'trim|required|is_natural');
$this->form_validation->set_message('required', '%s is required.');
$this->form_validation->set_message('valid_email', '%s is not a valid Email Address');
$this->form_validation->set_message('is_natural', '%s can only contain numbers.');
$this->form_validation->set_error_delimiters('<li>', '</li>');
if($this->form_validation->run() == FALSE)
{
redirect ('/');
}
else
{
echo '<pre>';
print_r($_POST);
echo '<pre>';
}
}
And this is the code I use in my view file:
<? if (validation_errors())
{
echo '<div id="validation_errors" title="Error:">';
echo '<div class="response-msgs errors ui-corner-all"><span>Errors:</span><br /><ul>';
echo validation_errors();
echo '</ul></div>';
echo '</div>';
}
?>
I found the way to do it. Redirecting does not keep the data to be shown. I used the code below to solve the problem:
if($this->form_validation->run() == FALSE)
{
$this->index();
}
I know it's a bit late but this method works wonders for me.
If you are validating your form in a different function than the one the form is loaded in, you can send your validation_errors() to any page that you redirect() by passing the validation_errors() method to $this->session->set_flashdata() like so:
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error', validation_errors());
redirect('/');
}
In your controller functions where you would like your errors or messages to be received you can then set them to the $data array like so:
if (!empty($this->session->flashdata('message'))) {
$data['message'] = $this->session->flashdata('message');
} elseif (!empty($this->session->flashdata('error'))) {
$data['error'] = $this->session->flashdata('error');
}
At the top of my views I usually include:
<?php if (isset($message)) {
echo '<p class="alert alert-info">'.$message.'</p>';
} elseif (isset($error)) {
echo '<p class="alert alert-danger"><strong>Error: </strong>'.$error.'</p>';
}?>
Using twitter bootstrap classes to format the messages helps to differentiate them.
I included the message flashdata so that you can see how whatever type of message or error you want to send, you are able to format them differently for all information, warning, success and error messages.
As per my comment:
function index()
{
$this->load->library('form_validation');
$data = array
(
'Param' => 'Value'
);
if($this->input->post('cellphone', true) !== false)
{
if($this->form_validation->run() != FALSE)
{
echo '<pre>' . print_r($_POST, true) . '</pre>';
}
}
$this->load->view('index', $data);
}
First, you need to change your form so it points to the current page, i.e. current_url() or site_url('controller/index').
When you go to the index without posting, it will simply skip the validation. Upon submitting your form, it will run the validation.
You can then use the built in form_error or validation_errors methods to display the errors within your index view.
finally i got a solution for the redirect with validation_errors
This is using to pass the validation_errors in the session data,
i do it like this
if ($this->form_validation->run()) {
$data = array(
'email' => $this->input->post('email'),
'is_login' => true
);
$this->session->set_userdata($data);
redirect($this->input->post('redirect'));
}
else
{
$data = array (
'errors' => validation_errors(),
'is_login' => false
);
$this->session->set_userdata($data);
redirect($this->input->post('redirect'));
}
and in the page i used
$this->session->set_flashdata('redirectToCurrent', current_url());
if ($this->session->userdata('is_login'))
{
echo "You are using this as : </br>" . $this->session->userdata('email');
echo "</br><a href='/logout'>Logout</a>";
}
else
{
echo form_open('login');
echo "" . $this->session->userdata('errors');
echo "email : " . form_input('email');
echo "Password : " . form_password('password');
echo form_submit('submit', 'Login');
echo form_hidden('redirect',$this->uri->uri_string());
echo form_close();
}
I wish you like this fast solution

repopulating the select list generated from database in codeigniter

Hi. I have the form in which I use form_validation If the user make any mistake (leave some required fields empty), user is redirected back to the form, and the form has been re-populated. All works, except my select , which is generated from the database.
Here is my code from the view:
echo "<select name='parentid'" . set_value("parentid"). ">";
echo '<option value = "0">None</option>';
foreach ($faq_categories as $row => $option) {
echo "<option value=" . $option['catid'] . ">" . $option['categoryname']. "</option>";
}
echo '</select>';
Here is my controller code:
public function displayAddFaqCategoryForm($error = null)
{
$data['title'] = "Add new FAQ Category";
$data['main_content'] = 'addFaqCategory';
$selectWhat = array('tname' => 'faq_categories',
'sortby'=> 'catid',
'how' => 'asc'
);
$this->load->model('selectRecords');
$data['faq_categories'] = $this->selectRecords->selectAllRecords($selectWhat);
$this->load->vars($data);
$this->load->view('backOffice/template');
} // end of function displayAddFaqCategoryForm
And here is the model code:
public function selectAllRecords($selectWhat = array())
{
$data = array();
$tname = $selectWhat['tname'];
$sortby = $selectWhat['sortby'];
$how = $selectWhat['how'];
$this->db->order_by($sortby,$how);
$query = $this->db->get($tname);
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectAllRecords
I am not getting any error messages, just the select is not repopulated with last used. Any help will be deeply appreciated.
You're using set_value() incorrectly
echo "<select name='parentid'" . set_value("parentid"). ">";
It's meant to output the actual value (for text inputs). This would produce something like:
<select name='parentid'ActualValue>
Which is not how a <select> element is populated, and is invalid HTML. See the correct usage in the Form Helper docs.
You can use set_select(), and it goes on your <option>:
foreach ($faq_categories as $row => $option) {
echo "<option value=".form_prep($option['catid']).'"';
echo set_select('parentid', $option['catid']); // outputs selected="selected"
echo ">".html_escape($option['categoryname'])."</option>";
}
I've taken a few other liberties with your code here as you can see, to be on the safe side (always).
If this is too much of a mess, you might be interested in the form_dropdown() function.

Resources