fetch value from url and pass it to another page in codeigniter - php

I have a url of a page as
http://localhost/projectname/admin/client/1
In the above url i have a form in which i need to fill details and save it in database. The form on this page is:
<?php
$data = array(
'type'=>'text',
'name'=>'job_title',
'value'=>'Job Title',
'class'=>'form-control');
?>
<?php echo form_input($data); ?>
<?php
$data = array(
'type'=>'submit',
'class'=>'btn',
'name'=>'submit',
'content'=>'Submit!'
);
echo form_button($data);
?>
<?php
echo form_close();
?>
On the submission of the page i wish to save it in a table but along with it i also wish to carry the id/value which is in url (in this case it is 1), and would like to carry it forward till model so that i can perform actions in database based on this id/value. Can anyone please tell how it can be done
Present code for controller
public function form()
{
$this->form_validation->set_rules('job_title','Full Name','trim|required|min_length[3]');
if($this->form_validation->run() == FALSE)
{
$regdata = array
(
'regerrors' => validation_errors()
);
$this->session->set_flashdata($regdata);
redirect('admin/clients');
}
else
{
if($this->user_model->job())
{
redirect ('admin/client');
}
}
}
Present code for model // In the users table i wish to add job title to that row where the id matches the value in url i.e 1
public function job()
{
$data = array(
'job_title' => $this->input->post('job_title')
);
$insert_data = $this->db->insert('users', $data);
return $insert_data;
}

Try some thing like this:
$clientId = $this->uri->segment('3'); // will return the third parameter of url
Now put this $clientId in form in a hidden input. Now you can get the $clientId on controller function when form submits. Pass it to model or use accordingly.

Related

Passing data from controller function to controller function before redirect

I am using codeigniter I have an edit page which shows me all information of a vacancy.
The (Vacancy) controller method to load this view looks like this, it makes sure all data is preloaded.
public function editVacancy($vacancyid)
{
$this->is_logged_in();
$this->load->model('vacancy/vacancies_model');
// Passing Variables
$data['title'] = 'Titletest';
$data['class'] = 'vacancy';
$orgadminuserid = $this->vacancies_model->getOrgAdminUserId($vacancyid);
if ((!is_null($orgadminuserid)) && ($this->auth_user_id == $orgadminuserid[0]->user_id)) {
$data['vacancyid'] = $vacancyid;
$data['vacancy'] = $this->vacancies_model->get($vacancyid);
$data['test'] = $this->session->flashdata('feedbackdata');
$partials = array('head' => '_master/header/head', 'navigation' => '_master/header/navigation_dashboard', 'content' => 'dashboard/vacancy/edit_vacancy', 'footer' => '_master/footer/footer');
$this->template->load('_master/master', $partials, $data);
}
}
In this view i have different forms for updating different sections.
Every form submit goes to a different method in my 'Vacancy' controller.
public function saveGeneralInfo()
{
$this->is_logged_in();
$this->load->model('vacancy/vacancies_model');
$vacancyid = $this->input->post('vacancyid');
$vacancyUpdateData = $this->vacancies_model->get($vacancyid);
$result = $this->vacancies_model->update($vacancyid, $vacancyUpdateData);
if ($result) {
$feedbackdata = array(
'type' => 'alert-success',
'icon' => 'fa-check-circle',
'title' => 'Success!',
'text' => 'De algemene vacature gegevens zijn geupdate.'
);
$this->session->set_flashdata('feedbackdata', $feedbackdata);
redirect("dashboard/vacancy/editVacancy/" . $vacancyid);
}
}
}
Where I indicated in my code "//HERE ..." is where I would want the feedback message parameter to pass on to my 'main controller method' which loads the view with the prefilled data. (editVacancy).
Is there a clean way to do this?
EDIT:
I tried using flashdata, i updated the code to have the flashdata inserted.
However when i do a var_dump($test); in my view, it remains null.
EDIT 2:
I noticed when i put my $_SESSION in a variable in my editVacancy controller method (which is being redirected to) and var_dump it in my view that this does not contain the ci_vars with the flashdata in.
Instead of using set_header you can use simple redirect function for it.
redirect("dashboard/vacancy/editVacancy/".$vacancyid);

CakePHP. Multiple Forms per page

I have website with few short News , to every News we can write a comment via Form. And there my problem occur.
When i fill my fields in one form, after pressing button, all forms are reloading without saving, and every field in every form must be filled out so they're treated like a one part how to avoid it ?
Additional info ( Info is my main modal with news, it's joined with Com modal)
index.ctp Form
<br><h5>Add comment:</h5><br>
<?php echo $this->Form->create('Com'); ?>
<?php echo $this->Form->input(__('mail',true),array('class'=>'form-control')); ?>
<?php echo $this->Form->input(__('body',true),array('class'=>'form-control')); ?>
<?php $this->request->data['ip'] = $this->request->clientIp(); ?>
<?php $this->request->data['info_id'] = $info['Info']['id']; ?>
<?php echo $this->Form->submit(__('Add comment',true),array('class'=>'btn btn-info')); ?>
<?php $this->Form->end(); ?>
controller ComsController.php
public function add()
{
if($this->request->is('post'))
{
$this->Infos_com->create();
$this->request->data['Infos_com']['ip'] = $this->request->clientIp();
$this->request->data['Infos_com']['id_infos'] = $number;
if($this->Infos_com->save($this->request->data))
{
$this->Session->setFlash(__('Comment is waiting for moderating',true),array('class'=>'alert alert-info'));
return $this->redirect(array('controller'=>'Infos','action'=>'index'));
}
$this->Session->setFlash(__('Niepowodzenie dodania komentarza',true),array('class'=>'alert alert-info'));
return TRUE;
}}
and Model Com.php, i comment lines to avoid neccesity of filling every field in forms
class Com extends AppModel
{
public $belongsTo = array('Info');
/*public $validate = array(
'mail'=>array(
'requierd'=>array(
'rule'=>array('notEmpty'),
'message'=>'Write your email'
)
),
'body'=>array(
'required'=>array(
'rule'=>array('notEmpty'),
'messages'=>'Write smth'
)
)
); */
}
I don't think you can access $this->request->data in a view (the data should be entered with a form, it was not submitted). You should use hidden fields to pass arguments like IP od id... Example:
echo $this->Form->input('Infos_com.client_id', array(
'type' => 'hidden',
'value' => $value
));
If you have multiple forms, it would be useful to separate their fields. For example:
echo $this->Form->input('Infos_com.' . $news_id . '.body', array('label' => __('body')));
This way you will get an array like:
$this->request->data['Infos_com'][$news_id]['body'].
And then you can make your logic in the model.

Saving data on GET request in CakePHP

I am building a simple mechanism where a user can like a post by clicking on a link. I'm using GET rather than POST as I want to allow the method to fire via the URL.
That been said how do I save data using GET? As the request data doesn't exist in this scenario... My model looks like:
class Like extends AppModel
{
public $name = 'Like';
public $belongsTo = array('User','Post');
}
and the method for adding looks like:
public function add( $id )
{
$post = $this->Post->find('first', array(
'conditions' => array('Post.id'=>Tiny::reverseTiny($id))
));
if (!$post)
{
throw new NotFoundException('404');
}
if($post['Post']['user_id'] == $this->Auth->user('id'))
{
$this->Session->setFlash('You can\'t like your own post... That\'s just silly!');
}
if ($this->Like->create())
{
$liked = $this->Like->find('first', array(
'conditions' => array('Like.id'=>Tiny::reverseTiny($id), 'Like.user_id'=>$this->Auth->user('id') )
));
if(!$liked){
$this->Like->saveField('user_id', $this->Auth->user('id'));
$this->Like->saveField('post_id', $post['Post']['id']);
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
} else {
$this->Session->setFlash('You already like this post!');
}
else
{
$this->Session->setFlash('Server broke!');
}
}
Can anyone help?
<?php echo $this->Html->link('1', array('controller'=>'followers','action'=>'add','id'=>Tiny::toTiny($post['Post']['id'])),
array('title'=>'Follow','class'=>'follow')); ?>
This part all works fine. It's saving a new row in the DB on GET that I'm struggling with.
Hi you just need to make a link to your controller action and pass you variable in the url.
to be clear the link on the post to like is in your post view :
$this->Html->link('like this post', array('controller' => 'like', 'action' => 'add', $postId))
It should render a link like this :
www.yourWebSite/likes/add/1 to like the postId 1,
variables after your action (add) are interpreted as variable for your controller action
if your fonction add had been
public function add($postId, $wathever){
}
the url should look like www.yourWebSite/likes/add/1/blabla
where 1 is the first var for the add action and blabla the second one and so on.
this is the equivalent of a non rewriting url : ?postId=1&whatever=blabla
EDIT :
if(!$liked){
//simulate the post behaviour
$this->request->data['Like']['user_id'] = $this->Auth->user('id');
$this->request->data['Like']['post_id'] = $post['Post']['id'];
//save the data
if ($this->Like->save($this->request->data)) {
$this->Session->setFlash(__('Thanks for your support !'));
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
} else {
$this->Session->setFlash('Server broke!');
}
}
How about using save with id=0 instead of create?
<?php
$like = array(
"Like" => array
(
"id" => 0,
"user_id" => $this->Auth->user("id"),
"post_id" => $post['Post']['id']
)
);
$result = $this->Like->save($like);
if(!$result){$this->Session->setFlash('Server broke!');}
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
?>

Codeigniter update form

I'm really new to CI and have been trying to create an update form class today, but I'm running into a dead end. I have my functions set up to create the form and publish the data to the database, I now need to be able to update this.
My edit form function is below:
public function edit_event()
{
$vars = array();
$data['form_url'] = $this->form_url;
if ($form_id = $this->EE->input->get('form_id'))
{
$data['form_id'] = $form_id;
}
return $this->EE->load->view('edit_event', $data, TRUE);
}
and the edit_event file loaded within the function is:
<?php
$this->EE=& get_instance();
$this->load->helper('form');
$attributes = array('class' => 'event_form', 'id' => 'my_event_form');
echo form_open($form_url.AMP.'method=update_form', $attributes);
$this->EE->load->library('table');
$this->EE->table->set_heading(
'Preference',
'Setting'
);
$query = $this->EE->db->query("SELECT * FROM exp_events WHERE id = '$form_id'");
foreach($query->result_array() as $row)
{
$this->EE->table->add_row(
form_label('Application Key', 'app_key'),
form_input('app_key',$row['app_key'])
);
$this->EE->table->add_row(
form_label('Access Token', 'access_token'),
form_input('access_token',$row['access_token'])
);
$this->EE->table->add_row(
form_label('User Key', 'user_key'),
form_input('user_key',$row['user_key'])
);
}
echo $this->EE->table->generate();
echo form_reset('reset', 'Clear Form');
echo form_submit('mysubmit', 'Submit Post!');
echo form_close();
?>
I then have my update form function:
public function update_form()
{
$form_id = $this->EE->input->get('form_id');
$data['form_id'] = $form_id;
$form_data = array(
'app_key' => $this->EE->input->post('app_key'),
'access_token' => $this->EE->input->post('access_token'),
'user_key' => $this->EE->input->post('user_key')
);
$this->EE->db->where('id', $form_id);
$this->EE->db->update('exp_events', $form_data);
$this->EE->functions->redirect($this->base_url);
}
When removing the $form_if option I can get the data to update, but it updates for every single item in the database. I obviously need this to only update the data with the form id of the form being edited.
As it stands, when I submit the update form, I get redirected to my $base_url which is correct, but no data gets updated, therefore I am clearly doing something wrong when defining the form id?
As I said I'm new to this, so if anyone notices any preferred methods feel free to let me know :).
Any pointers appreciated.
Thanks in advance.
Ben
You need to include a 'hidden' field in your form, with the form_id. At the moment your 'form_id' is not part of your input, so when you go and get the form_id it is failing.
change
echo $this->EE->table->generate();
echo form_reset('reset', 'Clear Form');
echo form_submit('mysubmit', 'Submit Post!');
to
echo $this->EE->table->generate();
echo form_hidden('form_id', $form_id);
echo form_reset('reset', 'Clear Form');
echo form_submit('mysubmit', 'Submit Post!');

how to get the value of form input box in codeigniter

value of FORM INPUT Help!!
//this is just a refrence of $nm and $fid from test_model//
$data['fid']['value'] = 0;
$data['nm'] = array('name'=>'fname',
'id'=>'id');
say i have one form_view with
<?=form_label('Insert Your Name :')?>
<?=form_input($nm)?>
and a function to get single row
function get($id){
$query = $this->db->getwhere('test',array('id'=>$id));
return $query->row_array();
}
then in controller.. index($id = 0)
and somewhere in index
if((int)$id > 0)
{
$q = $this->test_model->get($id);
$data['fid']['value'] = $q['id'];
$data['nm']['value'] = $q['name'];
}
and mysql table has something like 1. victor, 2. visible etc. as a name value
but here its not taking the value of name and id from form_input and not showing it again in form_view in same input box as victor etc so to update and post it back to database...
anyone please help!!
and please be easy as I am new to CI!!
Based on your comment to my first answer, here is a sample of a Controller, Model and View to update a user entry pulled from a table in a database.
Controller
class Users extends Controller
{
function Users()
{
parent::Controller();
}
function browse()
{
}
function edit($id)
{
// Fetch user by id
$user = $this->user_model->get_user($id);
// Form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run())
{
// Update user
$user['name'] = $this->input->post('name', true);
$this->user_model->update_user($user);
// Redirect to some other page
redirect('users/browse');
}
else
{
// Load edit view
$this->load->view('users/edit', array('user' => $user));
}
}
}
Model
class User_model extends Model
{
function User_model()
{
parent::Model();
}
function get_user($user_id)
{
$sql = 'select * from users where user_id=?';
$query = $this->db->query($sql, array($user_id));
return $query->row();
}
function update_user($user)
{
$this->db->where(array('user_id' => $user['user_id']));
$this->db->update('users', $user);
}
}
View
<?php echo form_open('users/edit/' . $user['user_id']); ?>
<div>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo set_value('name', $user['name']); ?>" />
</div>
<div>
<input type="submit" value="Update" />
</div>
<?php echo form_close(); ?>
It's hard to see the problem from your snippets of code, please try and give a little more information as to the structure of your app and where these code samples are placed.
Presume in the last code listing ('somewhere in index') you are getting $id from the form, but you define the ID of the form input box as 'id' array('name'=>'fname','id'=>'id') rather than an integer value so maybe this is where the problem lies.
Where does the $data array get passed to in the third code listing?
From your question I think you want to display a form to edit a person record in the database.
Controller code
// Normally data object is retrieved from the database
// This is just to simplify the code
$person = array('id' => 1, 'name' => 'stephenc');
// Pass to the view
$this->load->view('my_view_name', array('person' => $person));
View code
<?php echo form_label('Your name: ', 'name'); ?>
<?php echo form_input(array('name' => 'name', 'value' => $person['name'])); ?>
Don't forget to echo what is returned from form_label and form_input. This could be where you are going wrong.

Categories