如何在SilverStripe中将CheckboxsetField的结果格式化为逗号分隔字符串?

时间:2016-03-28 16:28:54

标签: silverstripe

我正在尝试为数据列表创建一些过滤器。我希望用户能够从标签列表中选择一个或多个过滤器,然后根据这些过滤器吐出对象列表。一切都很好,使用此代码根据发送的URL参数获取数据...

public function index(SS_HTTPRequest $request)
{
    // ...
    if($tagsParam = $request->getVar('tags')) {
        $articles = new ArrayList();
        $tagids = explode(",", $tagsParam);
        foreach($tagids AS $tagid) {
            $tag = Category::get()->byID($tagid);
            $articleitems = $tag->getManyManyComponents('Articles')->sort('Date DESC');
            foreach($articleitems AS $articleitem) {
                $articles->push($articleitem);
            }
        }
    }
    $data = array (
        'Articles' => $articles
    );
    if($request->isAjax()) {
        return $this->customise($data)->renderWith('ListItems');
    }
    return $data;
}

该代码适用于像mysite.com/?tags=1,2,3

这样的网址

我的问题是尝试根据使用CheckboxSetField构建的过滤器生成该URL。这是我的代码...

public function ArticlesSearchForm()
{
    $tagsmap = $this->getTags()->map('ID', 'Title')->toArray();
    $form = Form::create(
        $this,
        'ArticlesSearchForm',
        FieldList::create(
            CheckboxSetField::create('tags')
                ->setSource($tagsmap)
        ),
        FieldList::create(
            FormAction::create('doArticlesSearch','Search')
        )
    );

    $form->setFormMethod('GET')
        ->setFormAction($this->Link())
        ->disableSecurityToken()
        ->loadDataFrom($this->request->getVars());

    return $form;
}

当用户提交该表单时,生成的URL类似于mysite.com?tags%5B1%5D=1&tags%5B2%5D=2&action_doArticlesSearch=Search显然,它已经过去了值作为数组。如何传递一个简单的逗号分隔列表?

1 个答案:

答案 0 :(得分:2)

我建议您更改代码,而不是尝试更改CheckboxSetField的返回值。鉴于您将逗号分隔列表列表转换为已在此处的数组:

$tagids = explode(",", $tagsParam);

这样的事情,将跳过这一步:

public function index(SS_HTTPRequest $request)
{
    // ...
    if($tagsParam = $request->getVar('tags')) {
        $articles = new ArrayList();
        //This has a minor risk of going bad if $tagsParam is neither an
        //array of a comma-separated list
        $tagids = is_array($tags) ? $tagsParam : explode(",", $tagsParam);