Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter - Optional parameters

I'm building my first CodeIgniter application and I need to make URLs like follows:

controllername/{uf}/{city}

Example: /rj/rio-de-janeiro This example should give me 2 parameters: $uf ('rj') and $city ('rio-de-janeiro')

Another URL possible is:

controllername/{uf}/{page}

Example: /rj/3 This example should give me 2 parameters: $uf ('rj') and $page (3)

In other words, the parameters "city" and "page" are optionals. I can't pass something like '/uf/city/page'. I need always or 'city' OR 'page'. But I don't know how to configure these routes in CodeIgniter configuration to point to same method (or even to different methods).

like image 919
Silvio Delgado Avatar asked Sep 24 '13 04:09

Silvio Delgado


2 Answers

I've found the correct result:

$route['controllername/(:any)/(:any)/(:num)'] = 'ddd/index/$1/$2/$3';
$route['controllername/(:any)/(:num)'] = 'ddd/index/$1/null/$2'; // try 'null' or '0' (zero)
$route['controllername/(:any)'] = 'ddd/index/$1';

The Index method (inside "ControllerName") should be:

public function Index($uf = '', $slug = '', $pag = 0)
{
    // some code...

    if (intval($pag) > 0)
    {
        // pagination
    }

    if (!empty($slug))
    {
        // slug manipulation
    }
}

Hope it helps someone. Thank you all.

like image 68
Silvio Delgado Avatar answered Sep 25 '22 08:09

Silvio Delgado


public function my_test_function($not_optional_param, $optional_param = NULL)
  { 
   //do your stuff here
  }

have you tried this?

like image 24
Suvash sarker Avatar answered Sep 23 '22 08:09

Suvash sarker