I currently have a rule that allows for querying a couple different models according to name
, brandId
, and ingredients
. This rule works, except when I try to pass in an empty value for any of the optional parameters. I thought that I used the correct RegEx but apparently not. I've tried both:
array('ws/service/query', 'pattern'=>'ws/service/query/<model:\w+>/(<name:\w+>)?/(<brand:\d+>)?/(<ingredients:.+>)?', 'verb'=>'GET'),
and
array('ws/service/query', 'pattern'=>'ws/service/query/<model:\w+>/<name:(\w+)?>/<brand:(\d+)?>/<ingredients:(.+)?>', 'verb'=>'GET'),
to no avail. When I type the query string: /ws/service/query/myModel///
I get PHP Error - Undefined Index 'Model'. But when I use a query string like /ws/service/query/myModel/a/1/a
I get the desired result.
How do I allow the URL to accept null values for GET parameters?
Here is the action:
public function actionQuery()
{
$this->_checkAuth();
switch ($_GET['model'])
{
case 'dogFood':
$criteria = new CDbCriteria();
if ($_GET['name']) {
$criteria->addSearchCondition('name_df', $_GET['name']);
}
if ($_GET['ingredients']) {
$ingredientsArray = explode(',',$_GET['ingredients']);
foreach ($ingredientsArray as $ingredient) {
$criteria->addSearchCondition('ingredients_df', $ingredient);
}
}
if ($_GET['brand']) {
$criteria->addColumnCondition(array('brand_df' => $_GET['brand']));
}
$models = DogfoodDf::model()->findAll($criteria);
break;
default:
$this->_sendResponse(501, sprintf(
'Error: Mode <b>query</b> is not implemented for model <b>%s</b>',
$_GET['model']));
exit;
}
if (empty($models)) {
$this->_sendResponse(200,
sprintf('No items were found for model <b>%s</b>', $_GET['model']));
}
else {
$rows = array();
foreach ($models as $model) {
$rows[] = $model->attributes;
}
$this->_sendResponse(200, CJSON::encode($rows));
}
}