问题
My application is being built in a subdirectory of my local server, that looks something like this:
http://localhost/application/
The problem is that when I set the form action to "/form/save", the form routes to "localhost/form/save", which doesn't exist.
If I set the form action to "/application/form/save", I get an error, because Zend uses the URL input in its Front_Controller to pick the modules, Controllers, and Actions to use for requests.
Is there a simple way to have the base_url parsed out of requests? It works on everything else except for forms for some reason.
Another alternative would be having base_url added to all the form actions so your application can work in different environments, and then having it parsed out when the action is received by the controller.
Is there a simple way to set a variable to do something like this, already built into Zend? If not, what's a solution?
I can't seem to find anything addressing this issue anywhere.
回答1:
The problem is caused by including the initial slash in the action. When you set a link with a root-relative link, it is equivalent to setting an absolute link, when the destination anchor is under the same domain name. ("/form/save" is equivalent to "http://localhost/form/save").
In your case, it sounds like you need to add a base URL to the form, if you want to send the data to a different controller/action. You're using Zend_Form
(right?), the most elegant solution would be to subclass Zend_Form
, overridding the setAction()
method to prepend your base URL to every action you set.
class My_Form extends Zend_Form
{
...
public function setAction($action)
{
$baseAction = rtrim($this->_getBaseUrl(),'/') . $action; // Will remove a slash from the end of the base URL, so form actions start with a slash.
parent::setAction($baseAction);
}
private function _getBaseUrl()
{
// Retrive your base url from somewhere (config might be a good place).
}
}
Now whenever you create a new form from My_Form
and call My_Form::setAction()
you'll have your base URL automatically included.
Hope this helps.
回答2:
You could just leave the action blank and process the form data in the same action.
回答3:
I am new to Zend Framework so I do not know if this is the best solution, but it works fine for me.
I used the following code to set the action:
$url = new Zend_View_Helper_Url();
$this->setAction($url->url(array('controller'=> 'register','action'=>'index'),'default'));
来源:https://stackoverflow.com/questions/1640738/zend-form-set-action-can-it-work-w-zend-application-built-in-subdirectory