dscuu86620 2015-07-12 15:22
浏览 57
已采纳

Silverstripe扩展控制器操作

I'm trying to add a Controller Action to the Page_Controller class via an extension.

The desired result is to be able to go to www.mysite.com/setlanguage/spanish for instance and have that update the site's language to spanish via a browser cookie.

However I'm failry new to Extensions in SilverStripe and so far when I visit the link to the controller action all I get is a 404 error.

Please take a look at my code...

class Page_ControllerLanguageExtension extends Extension {

    private static $allowed_actions = array(
        'setLanguage'
    );

    public function setLanguage(SS_HTTPRequest $request) {

        $requestedLanguage = $request->param('ID');
        $languageCookie = new Cookie;
        $languageCookie->set('site_language', $requestedLanguage);

        return $this->owner->RedirectBack();

    }
}

And I'm calling in the extension with a YML config file:

Page_Controller:
  extensions:
    - Page_ControllerLanguageExtension

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • du1108 2015-07-15 11:03
    关注

    So if you need /setlanguage/<language> as the url you have to route the url /setlanguage/ to a seperate controller:

    class SetLanguageController extends Controller {
    
        public function index(SS_HTTPRequest $request) {
    
            $requestedLanguage = $request->param('Language'); //as defined in config below
            $languageCookie = new Cookie;
            $languageCookie->set('site_language', $requestedLanguage);
    
            return $this->RedirectBack();
    
        }
    }
    

    We don't need to define $allowed_actions in this case, cause action index is allowed by default.

    Now in your /mysite/_config/routes.yml you have to define the route to your controller:

    ---
    Name: mysite-routes
    After: framework/routes#coreroutes
    ---
    
    Director:
      rules:
        'setlanguage/$Language': 'SetLanguageController'
    

    See also: Docs for routing

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。