Welcome Guest, Not a member yet? Register   Sign In
Optional parameter for controller
#1

[eluser]JohnDoerther[/eluser]
Hi guys,

I have the following situation: I have a controller at/back/orders/start/15 which would in this case show the 15 latest orders placed.

Now, I created the start method in the controller with 1 parameter. This works great if I actually pass a parameter, but I also want to be able to access /back/orders/start without a parameter (and using a default value of for example 10).

Could you tell me what the cleanest way of doing this is? I have never worked with remap or URI routing, I am not even sure if I need this but a quick Google seems like I might need this.

I tried creating another function start without a parameter but this seems to be forbidden (duplicate function name).

Thanks in advance,
#2

[eluser]pickupman[/eluser]
Welcome to CI and the boards. You can use
Code:
$offset = $this->uri->segment(5,10); //Make 5th uri segment 10 by default
#3

[eluser]JohnDoerther[/eluser]
Thanks for the quick response, where would I use tha code? In the constructor or the actual function?
#4

[eluser]pickupman[/eluser]
In the actual function/method. Placing code in the constructor would be for things used throughout the entire controller.
Code:
function back(){
  $offset = $this->uri->segment(5,10);
}

I always put these at the top of the function/method. You can also pass uri segment default values by placing them in the arguments for the function
Code:
function at($third_segment = 'orders', $forth_segment = 'start', $fifth_segment = '10'){
  //Now each segment has a default value
}
The arguments need to be passed together in succession. (ie. you can just pass the 4th item, and not declare the ones before it.
#5

[eluser]JohnDoerther[/eluser]
Wow that last solution with the default parameter value works like a charm - thanks a bunch!

Again great help here on the forums, hope to be able to contribute one day myself!




Theme © iAndrew 2016 - Forum software by © MyBB