【问题标题】:ZF2 return dropdown value, not id in viewZF2 返回下拉值,而不是视图中的 id
【发布时间】:2014-11-17 12:00:25
【问题描述】:

ZF2 的新手。很确定这是一个非常基本的问题,因为我可以轻松地以程序方式完成,但发现文档很难完成。很高兴收到任何文档链接。

我将表单下拉值作为整数存储在数据库中。当我将结果返回到我的视图时,它使用以下方法返回整数:

echo $this->escapeHtml($user->system);

如何映射此响应以显示用户在表单中选择的下拉列表的实际值?

【问题讨论】:

  • 我假设您没有使用 ORM($user->system 是整数/外键而不是 System 对象)?
  • 不,据我所知,我没有使用 ORM。

标签: php zend-framework zend-framework2 zend-view


【解决方案1】:

一种选择是通过视图助手,尽管还有其他方法。

为任何“了解”系统的实体创建一个接口,例如SystemAwareInterface。 确保您的用户类(或任何其他类)实现此接口并返回系统 ID。

interface SystemAwareInterface {
   public function getSystemId();
}

创建一个视图助手,我假设顶级命名空间为System,并且您有某种服务可以通过它的身份从数据库中加载记录(让我们称之为SystemService,使用方法@ 987654325@)。

namespace System\View\Helper;

use System\Entity\SystemAwareInterface;
use System\Service\SystemService;
use Zend\View\Helper\AbstractHelper;

class System extends AbstractHelper
{
    // Service used to 'load' a system
    protected $systemService;

    public function __construct(SystemService $systemService)
    {
        $this->systemService = $systemService;
    }

    public function __invoke(SystemAwareInterface $entity = null)
    {
        if (0 === func_num_args()) {
            return $this;
        }
        return $this->render($entity);
    }

    public function render(SystemAwareInterface $entity)
    {
        return $this->systemService->loadById($entity->getSystemId());
    }

    public function getName(SystemAwareInterface $entity)
    {
        $system = $this->render($entity);

        return $system->getName();
    }
}

然后通过向getViewHelperConfig 添加工厂来向ViewHelperPluginManager 注册服务。

public function getViewHelperConfig()
{
    return array(
        'factories' => array(
            'System' => function($vpm) {
                $sm = $vpm->getServiceLocator();
                $service = $sm->get('System\Service\SystemService');

                return new View\Helper\Sysytem($service);
            }
        ),
    );
}

现在在视图脚本中,您可以使用帮助程序回显系统名称。

// echo out the name of the system
echo $this->system()->getName($user);

您还可以在新助手中使用其他视图助手;这样您就可以获得escapeHtml 帮助器并在getName() 方法中转义HTML 内容(我将把它留给您)。

【讨论】:

  • 非常感谢您的回答,非常清楚。我应该从一开始就更清楚,有一个名为user的模块,其中'system'只是数据库中的一个字段,就像'name'或'age'一样。我目前不在我的应用程序中使用名为 /entity/ 的文件夹。 user 模块的文件夹结构与 zftool 生成的默认文件夹结构相同。您能否编辑您的答案,以便我可以在 user 模块结构的上下文中看到它?抱歉,这个是新手。谢谢!
  • @anewvision entity 在 ZF2 中只是一个没有特定含义的文件夹/命名空间(model 往往是另一个流行的)。所以你可以在任何你喜欢的地方拥有这个界面,它只是在你的模块中组织代码,这样如果我开始处理你的项目,我会更好地知道你的域类在哪里等等。Service 等也是如此因此,如果您愿意,请继续创建它或给它另一个名称。唯一的先决条件是您有自动加载设置,我相信 ZFTool 无论如何都会为您解决这个问题。
  • 谢谢,这是有道理的,我是 ZF2 的新手,所以还在学习。但是我可以从您的评论中得到的是,结构没有我想象的那么相关,并且命名空间是关键。会接受你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 2012-06-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多