Tuesday, May 5, 2020

Observations about CHtml::link and regular links

I am using Yii and have links to several controllers.

I had normal links in the page that worked when I proceeded from the base URL. They failed after I clicked the Home button in the menu.

After clicking Home, the URL was .../index.php/site/index, referencing the site controller.

When I click the normal link,

   
  • Unit


  • it tries to access .../index.php/site/Unit and fails.

    When I click the CHtml::link in any of these formats,

       

  •    

  •    


  • it tries to access .../index.php/Unit/index and succeeds.

    When I click the modified CHtml::link,

       


  • it tries to access .../index.php/site/Unit/index and fails.

    The only one that works properly is the CHtml::link with an array for the destination URL.

    The normal URLs add to the existing URL, without noticing that index.php is the actual page and the rest of the URL is path info, so they fail.

    Looking at normalizeUrl and createUrl explain the reasons for the CHtml::links.

    • normalizeUrl is only called if the parameter is an array
    • $this->getId() returns the name of the current controller
    • $this->getAction()->getId() returns the name of the action for the current controller
    • The remaining items are from createUrl:
      • If the route parameters is empty, return the current URL
      • If the route does not contain a /, then replace the current action with / and the route
      • If the leading character in the route is not / and the current module is not null, then replace the current controller with the module and add the route
      • If the route has a site/action or /site, then create the URL from the Yii app, not the current controller
    Conclusion, when creating a link for a different controller, use CHtml::link with an array parameter so that the URL is created based on the Yii app and not the current controller.



      No comments:

      Post a Comment

      Followers