Edit and delete issues in codeigniter - php

I tried some of the steps here, but until now, my edit and delete functions do not work correctly. Can you please help me with it?
First, I have these lines in my client controller:
public function edit_job
{
$this->validateRole('client');
$this->load->model('job_model');
$id = $this->uri->segment(3);
$data['my_preference'] = $this->array_to_select( $this->job_model->get_all_categories(), 'id','name');
$data['job'] = $this->job_model->get_job($id);
$this->load->view('client/edit_job', $data);
}
public function delete_job()
{
$this->validateRole('client');
$this->load->model('job_model');
$id = $this->uri->segment(3);
$this->job_model->delete_job($id);
//echo '<script language="javascript">alert("Post successfully deleted.");</script>';
redirect('client/manage_jobs?message=Job post successfully deleted');
}
}
Then, I have these lines in my job_model
function edit_job()
{
$data = array(
'title' => $this->input->post('title'),
'category_id' => $this->input->post('category_id'),
'start_date' => date("m-d-Y", strtotime($this->input->post('start_date'))),
'description' => $this->input->post('description'),
);
$this->db->where('id', $this->input->post('id'));
$this->db->update('job', $data);
}
function delete_job($id)
{
$this->db->where('id', $id);
$this->db->delete('job', $data);
}
Currently, add job works quite well (although I sometimes have problem with the start date), but edit and delete do not work well. Whenever I press edit in my view page, it will show a page exactly similar to a new add_job page (so whenever I type and fill in the form, it will be added as a new job, not as a revision of a particular job) (I've been trying to echo the original values first before editing can be done, but it never worked. In terms of delete job, it does show the redirect message, but whenever I check the jobs available, the supposedly deleted job is still available.
I have been stuck here for quite some time now. Please help me..

I think asp_tags is disable in your php settings. Change your code as following:
<?php echo $this->uri->segment(3, 0); ?>
instead of
<?= $this->uri->segment(3, 0); ?>
and about delete, you don't need to pass second parameter in delete function. So do following:
$this->db->delete('job');
instead of
$this->db->delete('job', $data);

Related

Update Codeigniter form - refresh

I'm having a form which retrieves the values from the database and updates it by submitting the form.
First time when I'm accessing the page, it works, it retrieves the values, but if I'm updating the values through the form it retrieves the new values only after refreshing manually the page.
How can I refresh it automatically?
Also, if I'm accessing the page, not doing an update, and refreshing it, everything it's deleted, including the values form the database.
This is the controller:
public function edit_profile()
{
$id=$_SESSION['user_id'];
$this->load->model('retrieve');
$upd = array
(
'Name' => $this->input->post('name'),
'surname' => $this->input->post('surname'),
'Id_loc' => $this->input->post('id_loc')
);
$data['info']=$this->retrive->select_Info($id);
$this->retrieve->update_info($id,$upd);
$this->load->view('edit_profile', $data);
}
And this is the model:
function update_info($id,$data){
$this->db->where('id', $id);
$this->db->update('users', $data);
}
your code will look like this: with two functions
public function edit_profile()
{
$id=$_SESSION['user_id'];
$data['info']=$this->retrive->select_Info($id);
$this->load->view('edit_profile', $data);
}
public function saveUpdate()
{
$id=$_SESSION['user_id'];
$this->load->model('retrieve');
$upd = array
(
'Name' => $this->input->post('name'),
'surname' => $this->input->post('surname'),
'Id_loc' => $this->input->post('id_loc')
);
$update = $this->retrieve->update_info($id,$upd);
if($update)
{
redirect('YURCTRLER/edit_profile');
}
}
add the following code to your controller after an update is done:
redirect($this->uri->uri_string());
or
redirect('YOURCONTROLLER/edit_profile', 'refresh');
For the case of deleting, the code you have provided I think is not enough to deduce the problem :-(

Updating table fields on submit button

I am very much new to laravel framework.
I have one form , which i need to update on submit button click.
when submit button clicks control goes to controller.php 's update() function .
But I am unable to edit any field's value.
here is my code.
public function update($id)
{
//echo "<pre>";print_r(Input::all());exit;
$product = $this->product->find($id);
$input = Input::only('designer', 'sku', 'name', 'display_name', 'description', 'price', 'main_category', 'sub_category', 'lead_time', 'sizing', 'woven', 'body_fabric', 'lining_fabric', 'fit', 'primary_color', 'secondary_color', 'care_label', 'neck_type', 'closure', 'trims', 'special_finishings', 'image1', 'image2', 'image3', 'image4', 'image5','top', 'combo_products', 'keywords', 'visibility', 'featured');
//echo "<pre>";print_r($input);exit;
try
{
$this->adminNewProductForm->validate($input);
} catch(\Laracasts\Validation\FormValidationException $e)
{
return Redirect::back()->withInput()->withErrors($e->getErrors());
}
$slug = Str::slug(Input::get('name'));
$slug = $this->product->getSlug($slug);
$input = array_add($input, 'slug', $slug);
DB::transaction(function() use($product, $input)
{
$product->fill($input)->save();
$stock_count = 0;
if(!empty(Input::get('xsmall_size')))
{
$rows = DB::table('products_variants')->where('product_id', $product->id)->where('variant_name', 'XS')->get();
$stock_count += Input::get('xsmall_stock');
if(!empty($rows))
{
DB::table('products_variants')->where('product_id', $product->id)->where('variant_name', 'XS')->update(array('variant_specs' => Input::get('xsmall_size'), 'price_change' => Input::get('xsmall_price'), 'total_stock' => Input::get('xsmall_stock'), 'stock_used' => 0));
} else {
DB::table('products_variants')->insert(array('product_id' => $product->id, 'variant_name' => 'XS', 'variant_specs' => Input::get('xsmall_size'), 'price_change' => Input::get('xsmall_price'), 'total_stock' => Input::get('xsmall_stock'), 'stock_used' => 0));
}
}
$input = array();
$input['flagship_status'] = Input::get('flagship_status');
if(Input::get('flagship_status'))
{
$input['stock_count'] = Input::get('small_stock');
}else {
$input['stock_count'] = $stock_count;
}
$product->fill($input)->save();
});
//echo "<pre>";print_r(Input::all());exit;
return Redirect::back()->withFlashMessage('Product Updated Successfully!');
}
Also I cant understand , what is going on by this line ? because i did not find validate function anywhere in my code.
$this->adminNewProductForm->validate($input);
I need to update table products not products_variants.
validate is inherited from the FormRequst class.
https://laravel.com/api/5.0/Illuminate/Foundation/Http/FormRequest.html#method_validate
You've provided too much code and too little information. You said you need to update a specific table, but yet there are two lines where you are very intentionally manually updating a database entry.
This is one of them:
DB::table('products_variants')->where('product_id', $product->id)->where('variant_name', 'XS')->update(array('variant_specs' => Input::get('xsmall_size'), 'price_change' => Input::get('xsmall_price'), 'total_stock' => Input::get('xsmall_stock'), 'stock_used' => 0));
When you call this:
$product->fill($input)->save();
It also saves 'dirty' (modified) models that also belong to it, which can include products_variants relationships. From the sound of it, you are incorrectly applying changes directly through SQL, and then the model's save method is overwriting it.
You seem unclear about what your code is actually doing, and I would strongly suggest simplifying it down and adding in code as you begin to understand what each line does. I think your question is the byproduct of copying an example and adding your own work without understanding how Laravel handles relationships and models. There is almost never a good reason to use raw SQL or DB statements.

Editing more than one field in Codeigniter

Currently, editing profile works for me. However, my problem is, only one element is successfully edited. I can echo previously saved data, and I can even type and edit each of the textboxes. Problem is, only the revision made on "profile" field is properly reflected. All the other fields remain the same.
here's what I have so far:
in controller page:
public function edit_profile()
{
//loads client profile and allows editing to be done
$this->validateRole('client');
$this->load->model('job_model');
$id = $this->auth_model->get_user_id();
$data['client'] = $this->auth_model->get_client($id);
$this->load->view('client/edit_profile', $data);
}
public function edit_profile_submit()
{
$this->validateRole('client');
$this->load->model('auth_model');
//$this->auth_model->edit_client_profile($this->auth_model->get_user_id(), $_POST['tagline']);
$this->auth_model->edit_client_profile($this->auth_model->get_user_id(), $_POST['profile']);
//$this->auth_model->edit_client_profile($this->auth_model->get_user_id(), $_POST['billing_mode']);
redirect('client/view_profile?message=Profile updated.');
}
in model page:
public function edit_client_profile($id, $profile)
{
// allows client to edit his or her profile
$data = array(
//'tagline' => $tagline,
'profile' => $profile
//'billing_mode' => $billing_mode
);
$this->db->where('id', $id);
$this->db->update('client', $data);
}
I tried editing my controller and model page only to get errors so I commented the added lines for now instead.
I am looking forward to any possible help.
Thanks!
The error is probably because you have two undefined variables in your $data array each time you call the model. Instead of creating the array in your model, create it in your controller:
$data = array(
'tagline' => $_POST['tagline'],
'profile' => $_POST['profile'],
'billing_mode' => $_POST['billing_mode']
);
Then call the model
$this->auth_model->edit_client_profile($this->auth_model->get_user_id(), $data);
Remove the array creation from your model, change the second parameter being passed to $data:
public function edit_client_profile($id, $data)
{
$this->db->where('id', $id);
$this->db->update('client', $data);
}

Laravel 4: Unique(database) not validating

I am creating a basic CMS to teach myself the fundamentals of Laravel and PHP.
I have a 'pages' table and I am storing a url_title. I want this URL title to be unique for obvious reasons. However, whatever I do to validate it, fails. It just saves anyway. I'm sure it is something simple. Can you spot what is wrong with this code?
I am also using Former in the view, that doesn't validate either. I have tried hard-coding a value as the last option in the unique method and it fails also.
http://anahkiasen.github.io/former/
http://laravel.com/docs/validation#rule-unique
States: unique:table,column,except,idColumn
Here is my Controller:
public function store()
{
$validation = Pages::validate(Input::all());
if($validation->fails()) {
Former::withErrors($validation);
return View::make('myview');
} else {
Pages::create(array(
'title' => Input::get('title'),
'url_title' => Input::get('url_title'),
'status' => Input::get('status'),
'body' => Input::get('body'),
'seo_title' => Input::get('seo_title'),
'seo_description' => Input::get('seo_description')
));
//check which submit was clicked on
if(Input::get('save')) {
return Redirect::route('admin_pages')->with('message', 'Woo-hoo! page was created successfully!')->with('message_status', 'success');
}
elseif(Input::get('continue')) {
$id = $page->id;
return Redirect::route('admin_pages_edit', $id)->with('message', 'Woo-hoo! page was created successfully!')->with('message_status', 'success');
}
}
}
Here is my model:
class Pages extends Eloquent {
protected $guarded = array('id');
public static $rules = array(
'id' => 'unique:pages,url_title,{{$id}}'
);
public static function validate($data) {
return Validator::make($data, static::$rules);
}
}
I have tried the following:
public static $rules = array(
// 'id'=> 'unique:pages,url_title,{{$id}}'
// 'id'=> 'unique:pages,url_title,$id'
// 'id'=> 'unique:pages,url_title,:id'
// 'id'=> 'unique:pages,url_title,'. {{$id}}
// 'id'=> 'unique:pages,url_title,'. $id
);
Any ideas? I spoke to the guy who created Former. He can't make head nor tail about it either. He suggested tracking it back to find our what query Laravel uses to check the uniqueness and try running that directly in my DB to see what happens. I can't find the query to do this. Does anyone know where to track it down?
Many thanks
Your rule should be:
public static $rules = array(
'url_title' => 'unique:pages,url_title,{{$id}}'
);
As I guessed from your code Input::get('url_title')
You have to use the field name used in the form.
Thanks peeps. I have been using the Laravel unique solutions and it hasn't been working well. I found this package which solves the issue brilliantly.
https://github.com/cviebrock/eloquent-sluggable#eloquent
Definitely worth a look.
Thanks for your feedback.

Modify a row with CakePHP

I'm using CakePHP to show a frontend GUI for a MySQL database table. I've used bake to auto generate the screens and I currently have a fully functioning app with View, Edit and Delete buttons per row. I want to add a button per row, called Accept, which should set IsAccepted = 1 on the SQL row.
I've managed to add an Accept button per row as follows:
echo $this->Html->link(__('Accept'), array('action' => 'accept', $product['Product']['ID']))
But the code in ProductController.php does not work:
public function accept($id = null){
...
$this->Product->IsAccepted = 1; // does not work, silently fails
}
What am I doing wrong? How do I properly edit a row using a per-row button?
public function accept($id = null){
$this->Product->save(array('id' => $id, 'is_accepted' => 1));
}
// assuming cake 2.1+
public function accept($id = null){
if($this->Product->exists($id)) {
$this->Product->saveField('is_accepted', 1);
// success..
}
// else throw not found exception...
}
Thanks to cornelb I found the answer! This is the final code I used to modify a row, with a per-row button.
Modifies the row when the per-row button is pressed (works just like a POST/AJAX button)
A flash message that says "Accepted!" shows if saving succeeds
Redirects back to the listing page (appears to never leave the listing)
This is the code that goes in ProductController.php (or whatever controller class you have):
public function accept($id = null) {
if ($this->Product->exists($id)) {
// save the row
// you absolutely need to fill the 'id' slot, even if its not your primary key!!
// this ensures that the row is EDITED, and not INSERTED!
if($this->Product->save(array('id' => $id, 'ID' => $id, 'IsApproved' => 1, 'ApprovedDate' => date('Y-m-d H:i:s', time())))){
// show a "flash" message
// (not Adobe Flash, just a message that shows on top of the list)
$this->Session->setFlash(__('The product has been accepted!'));
// this action does not have a view so no need to render
$this->autoRender = false;
// redirect to index view
return $this->redirect(array('action' => 'index'));
}
}
}
**Try this.....**
<?php
public function accept($id = null) {
$this->autoRender = false; // if action has not view.
if ($this->Product->exists($id)) {
$this->Product->id = $id;
if ($this->Product->save(array('is_accepted' => 1))) {
$this->Session->setFlash(__('The product has been accepted!'));
return $this->redirect(array('action' => 'index'));
}
}
}
?>
Just run updateAll query from accept function as shown below:
public function accept($id = null){
if(!empty($id)){
$this->Product->updateAll(
array('Product.is_accepted' => 1),
array('Product.id' => $id)
);
}
}
Hope this will help you...
For reference: http://book.cakephp.org/2.0/en/models/saving-your-data.html

Categories