【问题标题】:Zend framework action helper or something else?Zend 框架动作助手或其他东西?
【发布时间】:2012-01-13 18:20:38
【问题描述】:

我的 zend 框架项目中需要链接选择框:Countrys->Regions->Provinces->Towns。

我正在使用 zend 表单并打算在其中一个更改时重新提交以重新加载链接选择框的内容。我在 PHPunit 测试中编写了一些代码来模拟我在控制器中需要的内容。 我将需要在我的网站上以多种不同的形式使用这种区域结构,并计划使用 AJAX 进行增强。

我不想复制这段代码,所以我应该将它存储在哪里以及应该如何构建它,以便我可以重用它的功能。我想也许是一个动作助手?

public function testCanGetRegionalStructureFromUser() {
        $user = new \Entities\User;
        $user = $this->em->getRepository('Entities\User')->findOneByEmail('testuser@yahoo.com');

        $town = new \Entities\Town;
        $town = $user->getTowns_id();

        // if user has not town input, then use the default 
        if (is_null($town)) {
            $config = Zend_Registry::get('config');
            $defaulttownid = $config->towns->defaultid;
            $town = $this->em->getRepository('Entities\Town')->find($defaulttownid);
        }

        // get the town id
        $townid = $town->getId();

        //get the province
        $province = $town->getProvinces_id();
        $provinceid = $province->getId();

        //get the region
        $region = $province->getRegions_id();
        $regionid = $region->getId();

        //get the country
        $country = $region->getCountries_id();
        $countryid = $country->getId();

        $countrylist = $this->em->getRepository('Entities\country')->findActiveCountries();
        $regionlist = $this->em->getRepository('Entities\Region')->findActiveRegions($countryid);
        $provincelist = $this->em->getRepository('Entities\Province')->findActiveProvinces($regionid);
        $townlist = $this->em->getRepository('Entities\Town')->findActiveTowns($provinceid);
    }

countrylist、regionlist 等已准备好作为选项注入到我的表单中,用于填充选择框。

【问题讨论】:

    标签: zend-framework zend-form


    【解决方案1】:

    我认为对于这种情况,创建复合 Zend_Form_Element 最有意义。

    这样,您只需几行代码即可轻松地将元素添加到表单中,您可以在元素中内置验证器,这样您就不会重复该逻辑,并且您可以使用自己的装饰器轻松控制选择的布局,只需更改一个文件即可反映对所有表单的更改。

    对于我的一个项目,我创建了一个复合元素,该元素具有一个纯文本框,该文本框使用自动完成功能在用户键入时实时搜索客户。从自动完成列表中选择客户后,将进行 ajax 调用,获取该客户拥有的属性列表,并使用新列表更新下拉框。

    元素提供对数据值(客户、属性)的访问,装饰器呈现组中的各个元素,并设置必要的事件处理程序和 ajax 调用(大部分代码位于外部 .js 文件中。

    Creating and Rendering Composite Elements
    Similar to the above reference, by Matthew Weier O'Phinney
    Video: Creating composite elements

    【讨论】:

    • 感谢您的信息。稍后我可能会在我的项目中使用复合元素,但在这种情况下我可能会使用动作助手。
    • 好的,你可能想要使用视图助手来代替,因为视图助手通常从视图中调用以输出 HTML 或视图逻辑,动作助手用于控制器中将常用功能注入控制器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多