Zend Form SetAction 使用命名路由 [英] Zend Form SetAction Using Named Routes
问题描述
我有一个要为其设置操作的表单.我想在我的表单文件(它扩展 Zend_Form)中而不是在控制器或视图中声明操作,使用我在引导程序中创建的路由.通常当我想使用路线时,我会做类似的事情
I have a form that I am trying to set the action for. I want to declare the action inside my form file (which extends Zend_Form) instead of in a controller or view, using a route I have created in my bootstrap. Usually when I want to use a route I do something like
$this->url(array(), 'route-name');
在视图中,或
$this->_helper->url(array(), 'route-name');
在控制器中.
如何从 Zend_Form 中调用路由?
How do I call a route from within Zend_Form?
我已经放弃尝试将路由加载到 zend_form 中.也许在未来的版本中可能会有一个功能可以轻松做到这一点?
edit: I have given up trying to load a route into zend_form. Perhaps in a future release there may be a function to easily do this?
我为我的表单创建了一个 viewScript 并在其中设置了路由:形式为init函数:
I have created a viewScript for my form and set the route in that: In the form init function:
$this->setDecorators(array(
'PrepareElements',
array(
'ViewScript', array(
'viewScript' => 'forms/formView.phtml'
))));
在视图文件中:
<form method="post" action="<?php echo $this->url(array(), 'route-name'); ?>" enctype="application/x-www-form-urlencoded">
<?php
foreach ($this->element->getElements() as $element)
{
echo $element;
}
?>
</form>
推荐答案
方法一:获取路由器
// in your form
public function init()
{
$router = Zend_Controller_Front::getInstance()->getRouter();
$url = $router->assemble(
array(
'paramterName0' => 'parameterValue0',
'paramterName1' => 'parameterValue1',
),
'routeName'
);
$this->setAction($url);
...
}
方法二:获取View对象的实例,直接调用url-view-helper
Method 2: Get an instance of the View object and call the url-view-helper directly
// in your form
public function init()
{
$url = Zend_Layout::getMvcInstance()->getView()->url(array(), 'routeName';
$this->setAction($url);
...
}
我更喜欢方法 1.它更冗长,但您的表单中的依赖项更少.
I prefer Method 1. It is more verbose but you have one dependency less in your form.
这篇关于Zend Form SetAction 使用命名路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!