2016-11-07 40 views
1

我有一些自定义的路由:自定义路由和处理表单提交

--- 
Name: mysiteroutes 
--- 
Director: 
    rules: 
    'signup//$Action/$Data/$Form': 'SignupController' 
--- 
Name: modelascontrollerroutes 
After: '#rootroutes' 
--- 
Director: 
    rules: 
    '': 'HomePage_Controller' 
    '$URLSegment/$Action/$ID': 'BaseController' 

并有注册控制器:

class SignupController extends Page_Controller { 

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

    public function index(SS_HTTPRequest $request) { 
     $form = Form::create(
      $this, 
      __FUNCTION__, 
      FieldList::create(
       EmailField::create('Email', 'Email') 
      ), 
      FieldList::create(
       FormAction::create('submit', 'Submit')->setAttribute('class', 'btn btn-success') 
      ), 
      RequiredFields::create('Email') 
     ); 
     return $this->customise(array('Form'=>$form))->renderWith(array("Signup", "Page")); 
    } 

    public function submit($data, $form = null) { 
     $form->addErrorMessage("Test", "Test error message",'bad'); 
     return $this->redirectBack(); 
    } 
} 

的形式呈现但是没有错误信息显示获得。当我去提交它(当然)SignupController /提交返回404。我已经添加setFormAction(Controller::join_links(BASE_URL, "signup", 'submit'))$form和数据通过但$form为空,我无法更新它。我可能会使它成为一个实例变量,但我可以使用正确的SS路由来解决这个问题。我应该更新我的路线以获得$form还是其他错误?

回答

2

您不需要$Data$Form参数在路由中,这些将在POST数据中。

其次,您不需要在allowed_actions中使用submit方法,因为它不会被路由触发。

要解决这个问题,你应该; 增加一个功能链接

public function link($action = null) 
{ 
    return $this->join_links('signup', $action); 
} 

所以,你将被重定向到signup/...

然后改变你的索引功能,这一点;

public function index() { 
    $form = Form::create(
     $this, 
     '', //so it will redirect you to 'signup', instead of 'signup/index'; I think it's prettier :) 
     FieldList::create(
      EmailField::create('Email', 'Email') 
     ), 
     FieldList::create(
      FormAction::create('submit', 'Submit') 
       ->setAttribute('class', 'btn btn-success') 
     ), 
     RequiredFields::create('Email') 
    ); 

    if($this->request->isPost()) 
     return $form; //return the form when it gets posted 

    return $this->customise(array('Form'=>$form))->renderWith(array("Signup", "Page")); 
}