Welcome Guest, Not a member yet? Register   Sign In
How to get method name in view ?
#1

(This post was last modified: 09-04-2023, 12:46 AM by sknair143.)

Hello,

I want to get the method name in the view to display a CSS class based on that.

I have a method like "employees/documents" (Employees - Controller, Documents - method)

In view how i can get the method name "documents" ?, is there any built-in function from codeigniter ?


Right now i created custom_helper.php :

PHP Code:
<?php

if (!function_exists("get_url")) {

    function get_url(): string
    
{

        $url $_SERVER['REQUEST_URI'];

        $exp explode("/"$url);


        return $exp[3];


    }







and in view 

Code:
<?php echo (get_url() == 'documents') ? 'active' : ''; ?>



This works !, but if any parameters come witht this url, i need to edit again. is there any alternative way which you can suggest ?
Reply
#2

You can get it from the router.
PHP Code:
\Config\Services::router()->methodName() 
Reply
#3

(09-04-2023, 01:09 AM)kenjis Wrote: You can get it from the router.
PHP Code:
\Config\Services::router()->methodName() 

Can i call this directly from view or i have to add in custom_helper code ?
Reply
#4

I recommend you create a custom helper.
Then, if the behavior of the router changes, you will need to update the helper code only.
Reply
#5

(09-04-2023, 01:25 AM)kenjis Wrote: I recommend you create a custom helper.
Then, if the behavior of the router changes, you will need to update the helper code only.

Okay, thanks.
Reply
#6

Here's a quick helper to get you going.

PHP Code:
<?php

/**
 *  getControllerName ()
 * -----------------------------------------------------------------------
 */
if ( ! function_exists('getControllerName'))
{
    /**
    * getControllerName ()
    * -------------------------------------------------------------------
    *
    * @return string
    */
    function getControllerName() : string
    
{
        $router service('router');
        return $router->controllerName();
    }
}

/**
 *  getMethodName ()
 * -----------------------------------------------------------------------
 */
if ( ! function_exists('getMethodName'))
{
    /**
    * getMethodName ()
    * -------------------------------------------------------------------
    *
    * @return string
    */
 
function getMethodName() : string
 
{
        $router service('router');
        return $router->methodName();
 }
}

// End of utility_helper Helper.

/**
 * -----------------------------------------------------------------------
 * Filename: utility_helper.php
 * Location: ./app/Helpers/utility_helper.php
 * -----------------------------------------------------------------------
 */ 
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB