Search code examples
routeshrefcodeigniter-4named-routing

codeigniter 4 routing named routes generates no href


I have a route that should generate an href for an anchor tag but I am getting no href:

<a href="" style="color:white !important" class="btn btn-info postlist">Update</a>

My code for above is :

data[i]["confirm"] = '<a href="<?=route_to('updatePost', 1) ?>" style="color:white !important" class="btn btn-info postlist">Update</a>';

My route is :

//$routes->add('post/(:id)', 'App/Controllers/Post::updatepost/$1');
$routes->add('post/(:id)', 'Post::updatepost/$1', ['as' => 'updatePost']);

I am expecting something like this

Noted: tried the unnamed and named way both didnt generate any href


Solution

  • The short answer is (:id) isn't supported. It's been deprecated in favour of using (:num)

    So the quick fix is to use (:num) instead of (:id)

    It is the same.

    A temp fix is to change a core file if you really really really need to.

    Disclaimer: It is STRONGLY ADVISED, NOT to alter Core Files. Do so at your own Risk

    In the file /system/Router/RouteCollection.php - LINE 117

    Was:

    /**
     * Defined placeholders that can be used
     * within the
     *
     * @var array
     */
    protected $placeholders = [
        'any'      => '.*',
        'segment'  => '[^/]+',
        'alphanum' => '[a-zA-Z0-9]+',
        'num'      => '[0-9]+',
        'alpha'    => '[a-zA-Z]+',
        'hash'     => '[^/]+',
    ];
    

    If you really need it, it Could be:

    /**
     * Defined placeholders that can be used
     * within the
     *
     * @var array
     */
    protected $placeholders = [
        'any'      => '.*',
        'segment'  => '[^/]+',
        'alphanum' => '[a-zA-Z0-9]+',
        'num'      => '[0-9]+',
        'alpha'    => '[a-zA-Z]+',
        'hash'     => '[^/]+',
        'id'       => '[0-9]+'
    ];
    

    The change is to add the 'id' entry which mimics the 'num'.

    It would be MUCH SAFER to simple Change all references to (:id) to (:num)