Welcome Guest, Not a member yet? Register   Sign In
index function with optional parameter
#1

[eluser]PermanaJ[/eluser]
I have a controller like this :

Code:
class Profile extends Controller{

    public function __construct() {
        parent::Controller();
    }

    public function index($profile_id = 0) {
        if($profile_id !== 0){
            // load profile
        }else{
            // list profile
        }
    }
}

The code above, when I open http://localhost/myapp/index.php/profile, it will list all user but when I open http://localhost/myapp/index.php/profile/23 it return 404 page not found

How can I make when visitor open http://localhost/myapp/index.php/profile, it will list all profile. But when visitor open
http://localhost/myapp/index.php/profile/23, it will show the detail of profile with Profile ID 23. Is it possible to do this without using routes ?
#2

[eluser]slowgary[/eluser]
The User Guide talks about CodeIgniter URL structure and passing parameters through to your controller. Check it out -> http://ellislab.com/codeigniter/user-gui.../urls.html
#3

[eluser]TheFuzzy0ne[/eluser]
You'd need to set up a route, or call your page like this:

http://localhost/myapp/index.php/profile/index/23

Otherwise CodeIgniter looks for a method named "23".
#4

[eluser]slowgary[/eluser]
Oops, my badSmile You can use the _remap() function to do this as well.
#5

[eluser]PermanaJ[/eluser]
What would be in the _remap ? I'm not too understand with _remap ...
#6

[eluser]slowgary[/eluser]
The _remap() function allows you to change how CodeIgniter URLs work. No matter what the URL is, if the _remap() function exists in your controller it will get called. CI will pass the second parameter to the _remap() function, and _remap() can decide which function to call.

Check it out in the user guide: http://ellislab.com/codeigniter/user-gui...#remapping

So you could do something like this:

Code:
function _remap($second_parameter)
{
   if(ctype_digit($second_parameter))
   {
      show_profile($second_parameter);
   }
   else
   {
      $second_parameter();
   }
}

I wouldn't use this exact example because it allows the user to call ANY php function through the URL, but you get the idea (I hope).
#7

[eluser]PermanaJ[/eluser]
Hmmm ... thank you very much for the help ... yep, now I get the idea using _remap()




Theme © iAndrew 2016 - Forum software by © MyBB