簡単なアプリをセットアップしただけで、うまく機能しているようです。私の createAction() は次のようになります。
public function createAction()
{
$entity = new Pokemon();
$request = $this->getRequest();
$form = $this->createForm(new PokemonType(), $entity);
$form->bindRequest($request);
if ($entity->getName() == "pikachu")
{
$this->container->get("session")->setFlash("error", "Pikachu is not allowed");
$url = $this->getRequest()->headers->get("referer");
return new RedirectResponse($url);
}
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('pokemon_show', array('id' => $entity->getId())));
}
return $this->render('BulbasaurBundle:Pokemon:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
));
}
フローは次のとおりです。
- ユーザーは /new に移動します
- ユーザーが「ピカチュウ」の無効なオプションを入力しました
- ユーザーが送信をクリックする (/create への POST)
- アプリケーションはエントリを拒否し、フラッシュ メッセージを追加して、/new にリダイレクトします。
- /new が表示され、フラッシュ メッセージが表示される
いくつかの確認事項:
/demo/{entityId}/edit
実際に機能するためのルートはありますか?(つまり、ブラウザに入力した場合、実際に期待する場所に移動しますか?)
異なるリダイレクト/転送を連鎖させていますか? URL にリダイレクトするコントローラーがあり、その URL を担当するコントローラーも別の場所にリダイレクトすると、予期しない (ただし正しい) 動作が発生することに気付きました。代わりに転送を使用して、この問題を修正しました。
つまり、他のすべてが失敗した場合は、コントローラーの redirect() メソッドを使用してリダイレクトを管理できます。
public function createAction()
{
...
return $this->redirect($this->generateUrl("pokemon_new"));
...
}