Welcome Guest, Not a member yet? Register   Sign In
Best way to add/edit a listing
#1

[eluser]CIfan1000[/eluser]
Hi,

I've been trying to figure out how to do this for a few days, and any help would be much appreicated:

I would like to have a single controller that can add or edit a user's listing. A listing in this case is something the user has for sale. A user can have multiple listings.

I thought of passing parameters in segments to the controller - including 2 segments that would pass as 2 parameters to the controller's index function. eg:

to edit a listing: controller/index/edit/listingID
to add a listing: controller/index/add/null

That worked great until I submitted the form - the action/destination of the form is the name of the controller, and does not have the parameters in it, so I get an error message saying the parameters for the index function are missing.

Then I thought of having an edit function and an add function in the controller, but then I don't know how to do the validation and loading of the view in a single function, such as the index function.

I would be grateful to hear from anyone who has done this.

Thanks!
#2

[eluser]Rick Jolly[/eluser]
I don't have an add or edit parameter or function. I just assume edit if there is an id. If editing, the url and form action would look like this: controller/index/listingID (only I'd use a route to eliminate the "index" method part). So you know if you are editing if the id is passed as a parameter. You can test if the form has been submitted (to do the validation) in a number of ways, but I usually just do this:
Code:
if (! empty($_POST)) ...
#3

[eluser]CIfan1000[/eluser]
Thanks Rick for your quick and helpful response!

It makes a lot of sense! But if you don't mind, let me try and confirm what I think you are saying.

If adding a listing, make the URL of the controller controller/index/Null
If editing a listing, make the URL of the controller controller/index/listingID

And then, in the controller, one can modify the action url of the form:

If adding a listing, make the action of the form controller/index/Null
If editing a listing, make the action of the form controller/index/listingID

Would that be correct?

I guess I could replace Null above with "add".

Thanks!
#4

[eluser]Rick Jolly[/eluser]
No need for the null parameter. Just use a default parameter in the index method signature.
Code:
function index($id = null)
{
   if (isset($id))
   {
       // editing
   }
   else
   {
       // adding
   }
}
#5

[eluser]Crimp[/eluser]
I do this the exact same way: using the presence of segment 3 as a switch.

However, I do pass an action variable to the view, $data['action'] = new or edit, to make it easier to keep up with the code.

I use this to keep multiple versions of the "same" form in the same view.

One example would be a user registration/profile form where new sign-ups require username, password and repeat password and the edit version requires old password, new password and repeat new password.

I then set all those fields in the view based on the action var.
#6

[eluser]CIfan1000[/eluser]
Dear Rick - I wasnt aware of being able to set the parameter to null in the function. I'm a bit of a newbie.

Dear Crimp - Modifying the view makes a lot of sense also.

Thanks to both of you for your time and effort - with your suggestions I now have what I need to proceed!

PS before I made this post, I was looking at http://codeigniter.com/wiki/Add_Edit_Views/

I think your suggestions will lead me to a more elegant solution than this one.

Take care!
#7

[eluser]Rick Jolly[/eluser]
[quote author="CIfan1000" date="1225558135"]
PS before I made this post, I was looking at http://codeigniter.com/wiki/Add_Edit_Views/
[/quote]
Yea, there are a couple of problems with that code.

The following doesn't make sense:
Code:
function edit($department_id = NULL){
   if($department_id == NULL){ $department_id = $this->uri->segment(3); }
The $department_id parameter in the edit function would be segment 3. It's a redundant check. Also, there is no check to be sure that a record is returned from the database (that the $department_id was valid).

Another problem is the seperate save() method for the post action. What if that method was accessed via the url? There is no error checking to detect that.
#8

[eluser]CIfan1000[/eluser]
Hey Rick,

Yeah, I agree with you. I don't think this example is very good.

What I also noticed is that the action url of the form is departments/save, but the views are loaded in the add or edit functions. Maybe I don't fully understand the code, but is seems to me that when the user hits Submit, the view including the form is not reloaded, which it would have to be if there were validation errors.

I hadn't thought as yet of checking that the record is actually in the db before trying to retrieve the whole record - so thanks again for another good suggestion.

Also, I store the userID with each listing (one has to) and I am thinking of checking the session based userID of the actual user against the userID in the listing, for security purposes, in case the session has been hijacked. What do you think?
#9

[eluser]Rick Jolly[/eluser]
[quote author="CIfan1000" date="1225576684"]
What I also noticed is that the action url of the form is departments/save, but the views are loaded in the add or edit functions. Maybe I don't fully understand the code, but is seems to me that when the user hits Submit, the view including the form is not reloaded, which it would have to be if there were validation errors.
[/quote]
Well, actually in that example the add or edit methods are called to redisplay the view if validation fails.

[quote author="CIfan1000" date="1225576684"]
I hadn't thought as yet of checking that the record is actually in the db before trying to retrieve the whole record - so thanks again for another good suggestion.
[/quote]
I wouldn't check if a record exists before getting the record, as that is 2 queries. What I'd do is validate that the id is a positive integer first (that could be done with a route or in the code), then get the record. But there needs to be some logic to handle the case where no record is returned (in the case of an invalid id). For example, redirect, show an error in the view, or show a 404 page. The code example doesn't handle that case.

[quote author="CIfan1000" date="1225576684"]
Also, I store the userID with each listing (one has to) and I am thinking of checking the session based userID of the actual user against the userID in the listing, for security purposes, in case the session has been hijacked. What do you think?[/quote]
I'm not sure that I understand, but if the logged in user can only access listings by their id, then you'd always need to include the user id from the session in the query. You wouldn't have a choice.
#10

[eluser]CIfan1000[/eluser]
Done!

Hi Rick,

Thanks to your help I went from clueless yesterday to having a functional add/edit controller/view today.

I threw the code below together in the last few hours and you will see it uses many of your suggestions.

Thank you so much for sharing your expertise! The code may look somewhat amatuerish to you - I am a mid forties guy who does this as a sideline to generate extra income - so it is not as professional as a pro coder.

But I tested it out and it works fine - although it is still preliminary and I am sure I will refine it.

I did the validation a little differently than you suggested - I do it whether or not the user has posted and I load the form view if the validation fails - it also fails if the user has not posted.

If I did validation when the user posted I then I could not initially display my form, since the user would not have posted.

I need to post the code into 2 posts - otherwise I reach the 6000 character max limit.

Please don't think I am asking you to review it - I am grateful for the time your time and don't mean to take more, but only if you feel like it, let me know what you think....

Code:
<?php

    // Make sure this is the very first line for security purposes:
    if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Listing extends Controller
{

    function index($ListingID = Null)  // Initialize ListingID to null if no value is passed to it
       {
            
            // --------------------------------------------------------------------------
            if (isset($ListingID))  // If the $ListingID is set then it contains a number and the listing needs to be edited
                {
                    $Action = "Edit";
                }
            else                    // If the $ListingID is NOT set then a listing needs to be added
                {
                    $Action = "Add";
                }
                

            // --------------------------------------------------------------------------
            //If user has NOT pressed Submit button:
            if (!isset($_POST ["ListingSubmitButton"]) )  //This must be name of button in form
                {

                    // If adding, and not pressed submit button
                    // Then populate blanks into form fields:
                    if ($Action == "Add")
                        {
                            $ListingTitle = "";
                            $ListingCityTown = "";
                        }
                        

                    // If editing, and not pressed submit button
                    // Then populate fields from db/table into form fields:
                    if ($Action == "Edit")
                        {

                            // Get the fields from the $ListingID passed to the index function:
                            $query = $this->db->query(" SELECT * FROM listings WHERE ListingID ='{$ListingID}' ");

                            if ($query->num_rows() > 0)
                                {
                                   foreach ($query->result() as $row)
                                   {
                                      $ListingTitle = $row->Title;
                                      $ListingCityTown = $row->CityTown;
                                   }
                                }
                        }
                        
                }
                
            else //If user HAS pressed Submit button:
                {

                    // Get postings into variables to populate form with post info
                    $ListingTitle = $this->input->post('ListingTitle');
                    $ListingCityTown = $this->input->post('ListingCityTown');
                    
                } // End of If user has NOT pressed Submit button




Theme © iAndrew 2016 - Forum software by © MyBB