views:

68

answers:

1

Hi there,

Lets say I have the following Request URI: /controller/action/filter//

When I call $this->_getParam('filter') in the controller, it will return NULL. However, I want it to return an empty string. Am I missing something obvious?

A: 

_getParam() can take a second optional argument holding a default return value. See the note here: http://framework.zend.com/manual/en/zend.controller.action.html#zend.controller.action.accessors

So $this->_getParam('filter','') should probably do what you need.

Edit: thanks for the clarification, gotcha. Not sure sure there's a particularly clean way to do what you want - looking at the code for Zend_Controller_Request_Abstract I can see it explicitly deletes the key from the parameter list if it has no value, so there's no easy way to tell if it was ever there from the controller. Something like the following will do the job, but gets a little ugly (you might be better off using an explicit 'reset' value for your filter parameter so you can capture it in a more sane fashion, rather than just an empty string, if that's possible?).

// if '/filter/' is in the request URI, but has no value
if (strpos($_SERVER["REQUEST_URI"],'/filter/') && !$this->_hasParam('filter'))
{
  // code to reset filter
}
// if filter is in the request *and* has a value
elseif ($this->_hasParam('filter'))
{
  // code to use filter value from request
}
else
{
  // code to get filter from session
}
Will Prescott
I know the second argument is a default value. However, when the parameter "filter" is not set in the URL, it will return ''. This means I can't check if the parameter was given based on the return value.When the filter param was not given, it should get the filter from the session. When the filter param is empty, it should clear the filter.
I am aware I could solve it by actually checking the REQUEST_URI, but I was hoping for a more elegant solution. Thanks for pointing out there probably isn't a better way.