SilverStripe - 使用函数获取页面的表单值

SilverStripe - Get a page's form value with a function

在 SilverStripe 3.1 中,我正在尝试获取我的 Hello Bar 的值 select 或让整个站点的页面都可以访问它。

我已经为 select HomePage.php 上的内容创建了下拉字段,因此我可以毫无问题地引用主页上的字段值。下拉列表的值将通知 if 块 运行 以及用什么填充问候栏。

Page.php

..//

public function HelloBarSelector() {
    $Selector = HomePage::get()->HelloBarSelect;
    return $Selector;
}

public function ShowHelloBar($itemID = 1) {
    $HelloBars = HelloBar::get()->byID($itemID);
    $HelloBars = $HelloBars->HelloBarText;
    return $HelloBars;
}

..//

Includes/HelloBar.ss

<% if $HelloBarSelector %>
<section class="hello">
    <p class="hello__text">$ShowHelloBar($HelloBarSelector)</p>
</section>
<% end_if %>

主页Page.php

..//

public function getCMSFields(){
    $fields = parent::getCMSFields();
    $fields->addFieldToTab('Root.HelloBar', GridField::create(
        'HelloBars',
        'Hello Bar Text', 
        $this->HelloBars(),
        GridFieldConfig_RecordEditor::create()
    ));
    $fields->addFieldToTab('Root.HelloBar', DropdownField::create(
            'HelloBarSelect',
            'Choose Your Hello Bar (this will be sitewide)',
            HelloBar::get()->map('ID', 'HelloBarText')
        )
        ->setEmptyString('(none)'));
    return $fields;
}

..//

我在主页上使用 $HelloBarSelect 访问该值没有任何问题,并且所有工作都按预期进行。看来问题是使用我的函数访问 $HelloBarSelect

ShowHelloBar() 函数有什么作用?

尝试只使用 $HelloBarSelector 而不是 $ShowHelloBar($HelloBarSelector)

编辑:

我明白了。模板函数不接受参数,因此在这种情况下,$itemID 将始终为空。

你从哪里得到 $itemID?如果它在 request/query 中的某处,那么您必须从中获取它。

例如

public function ShowHelloBar() {
    //If you use the standard $Action/$ID/$OtherID handler
    $itemID = $this->getRequest()->param('ID'); 

    //If it's somewhere in $_GET like ?ID=3
    $itemID = $this->getRequest()->getVar('ID'); 

    $HelloBars = HelloBar::get()->byID($itemID);
    $HelloBars = $HelloBars->HelloBarText;
    return $HelloBars;
}

HomePage::get() 将 return 主页数据对象的数据列表,因此您无法访问 HelloBarSelect。

HomePage::get()->First()HomePage::get_one()(假设您只有一个主页)将 return 一个 DataOject。因此,如果字段正确,您可以使用 HomePage::get()->First()->HelloBarText

提示:

使用Debug::dump(HomePage::get()) 看看你在操纵什么。转储数据以查看您的工作总是好的。

另请阅读:http://doc.silverstripe.org/en/developer_guides/model/ or watch these videos http://www.silverstripe.org/learn/lessons/