加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – zf2 form:使用来自数据库的数据填充select字段

发布时间:2020-12-13 21:47:18 所属栏目:PHP教程 来源:网络整理
导读:我正在学习zf2,我正面临一个涉及2个(最终更多)模块一起工作的问题.请注意,我仔细阅读了 this post(及相关的),这对我帮助很大.我将解释一下这个问题: 使用第一个模块(FrOption),管理员可以管理网站表单选项.所有选项都存储在db表中,如下所示: ID | FIELD_NA
我正在学习zf2,我正面临一个涉及2个(最终更多)模块一起工作的问题.请注意,我仔细阅读了 this post(及相关的),这对我帮助很大.我将解释一下这个问题:

>使用第一个模块(FrOption),管理员可以管理网站表单选项.所有选项都存储在db表中,如下所示:

ID | FIELD_NAME | FIELD_VALUE
1 |国内|德国|
2 |国内|法国|
3 |性别|男|
4 |性别|女|
5 | TIPO |汽车|
6 | TIPO |飞|

>在我的模块(FrItem)中,我构建了一个需要一些“field_name”字段的表单.
我的“项目”表格如下:

ID |名称| id_tipo |
1 |菲亚特| 5 |
2 |莎| 6 |
3 |福特| 5 |
4 |法国航空6 |

(id_tipo是一个选项FK)

还要考虑:

>我的实体有“tipo”属性,setter getter
>我已经构建了一个ItemHydrator来将id_tipo db字段“映射”为“tipo”实体属性
>作为测试,我在表单类中添加了这个字段,在视图和编辑模式下一切正常:

$this->add(
'type' => 'ZendFormElementSelect','name' => 'id_tipo','options' => array (
    'label' => 'Tipo','empty_option' => 'Select','value_options' => array ('5' => 'Car','6' => 'Fly' ) )

);

现在我想“链接”这两个模块:value_options应该是来自FrOption的动态数组,所以我正在寻找实现这个要求的最佳方法.

我认为一个解决方案可能是这样的:

>添加到我的FrOption / src / FrOption / Service / FrOption.php服务类getOptionByName($fieldName)方法
>在FrItem / Module.php中检索服务,然后使用getOptionByName将数据全部注入到Form中.

这可能是一个明智和有效的解决方案吗?在性能方面你对它有什么看法(选项表可以增长)?
如果有的话,你用什么样的解决方案来解决类似的问题?

谢谢

解决方法

This can be done easily by following the below 2 steps in Zend
Framework2 Step 1.

add The instance of the adapter what instantiating form class in the
controller action

$dbAdapter = $this->getServiceLocator()->get('ZendDbAdapterAdapter');
$form = new TestForm ($dbAdapter);

Step 2 in your form

namespace TestForm;

use ZendFormForm;
use ZendDbAdapterAdapterInterface;
use ZendDbAdapterAdapter;
class TestForm extends Form
{
    protected $adapter;
    public function __construct(AdapterInterface $dbAdapter)
    {
        $this->adapter =$dbAdapter;
                parent::__construct("Test Form");
        $this->setAttribute('method','post');
                //your select field
$this->add(array(
                'type' => 'ZendFormElementSelect','name' => 'name','tabindex' =>2,'options' => array(
                        'label' => 'Author','empty_option' => 'Please select an author','value_options' => $this->getOptionsForSelect(),)
        ));

                // another fields

}
       public function getOptionsForSelect()
    {
        $dbAdapter = $this->adapter;
        $sql       = 'SELECT id,name  FROM newsauthor where active=1 ORDER BY sortorder ASC';
        $statement = $dbAdapter->query($sql);
        $result    = $statement->execute();

        $selectData = array();

        foreach ($result as $res) {
            $selectData[$res['id']] = $res['name'];
        }
        return $selectData;
    }

}

And here you go you are ready to rock.I hope it helps you

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读