Welcome Guest, Not a member yet? Register   Sign In
Handling controller parameters
#1

Hello,

I have a controller to display a table, which allows sorting, filtering, editing, pagination... That leads to a few URL parameters: sort column, sort ascending/descending, row offset, filter,... Some of them are optional. For example, usually I will not need a filter. What is the best way to handle that?

My 'edit' function looks like this:

Code:
public function edit($order, $dir, $offset){
        if ($this->uri->total_segments() == 7){
            $filter = $this->uri->segment(6);
            $id = $this->uri->segment(7);
        }else{
            $filter = '';
            $id = $this->uri->segment(6);
        }
        ..... //Edit $id
}

Is this the correct way to do it?

Thanks!
Reply
#2

See the second parameter in the Users Guide:

segment()
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

I usually define all of the permitted URL parameters on the method definition, with default values set for optional parameters. If it's possible for the order of the parameters to change, I might use logic similar to what you've shown to reassign the values to the correct variables. However, I try to avoid that level of complexity whenever possible.

As InsiteFX inferred, the second parameter of $this->uri->segment() can be very useful for handling optional parameters, though the code you've shown here wouldn't benefit from that.
Reply
#4

A (perhaps clumsy) simple way to do this, if you do not know the order of the items in the url, or how many, are coming in on the url is to have something like

PHP Code:
public function edit($option1=FALSE$data1=FALSE$option2=FALSE$data2=FALSE$option3=FALSE$data3=FALSE){

 
  // then deal with the options and data how you want



To interpret the options (and you can do this lots of different ways) you can say something like if option1=order then do_order=TRUE and do_order_type = $data1 ('asc' or 'desc' for example). Or you can run each option through a switch to set the actions to take place and associated rules, or you can call a seperate function on each option which sets them, or you can just repeat the checks for each option. The point is option1 can be 'order', or 'dir' or 'offset' and data1 would be the data associated with that command.

Hope that helps,

Paul.
Reply
#5

Thanks for your hints.

As mwhitney pointed out, I can't take advantage of the second parameter of segment() in this function. Maybe it's time to try to give the parameters a fixed order.

Thanks Paul for your idea too.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB