ZF2:如何从db下载选项

时间:2012-09-09 17:11:11

标签: php zend-framework2

我跟着tutorial。但是我找不到从这样的数据库中填充表单选择的方法:

// Blog/src/Blog/Form/BlogItemForm.php
$blogCategoryTable = new Model\BlogCategoryTable;
$this->add(new Element\Select('category_id',
    array('label' => 'Category', 'value_options' => $blogCategoryTable->getFormChoices())
    ));

有没有人有任何想法?

1 个答案:

答案 0 :(得分:5)

我使用函数检索数据并将其设置为以下形式:

来自我的工厂:

    $option_for_select = $this->model->getWhatEver();
    $this->add($factory->createElement(array(
        'name' => 'what_ever',
        'type' => 'Zend\Form\Element\Select',
        'attributes' => array(
            'options' => $option_for_select,
        ),
        'options' => array(
            'label' => 'What ever:',
        ),
    )));

来自模特:

public function getWhatEver()
{
    $sql = "SELECT something";
    $statement = $this->adapter->query($sql);
    $res =  $statement->execute();

    // set the first option
    $rows[0] = array (
        'value' => '0',
        'label' => 'Top',
        'selected' => TRUE,
        'disabled' => FALSE
    );

    foreach ($res as $row) {
        $rows[$row['triplet_id']] = array (
            'value' => $row['col1'],
            'label' => $row['col2'],
        );
    }
    return $rows;
}