ZF2 return dropdown value, not id in view

88 views Asked by At

New to ZF2. Pretty sure this is a very basic question as I can easily do it in procedural style, but finding the documentation difficult to work through. Any documentation links gladly received.

I am storing a form dropdown value as an integer, in the db. When I return the results to my view it is returning the integer using:

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

How do I map this response so that I show the actual value of the dropdown that the user selected in the form?

1

There are 1 answers

3
AlexP On BEST ANSWER

One option would be via a view helper, although there are other ways.

Create an interface for any entity that is 'aware' of the system, say SystemAwareInterface. Ensure your user class (or any other class) implements this interface and returns the system id.

interface SystemAwareInterface {
   public function getSystemId();
}

Create a view helper, i'm assuming a top level namespace of System and that you have some kind of service that can load the record from the database by it's identity (lets call it SystemService with a method loadById()).

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();
    }
}

Then register the service with the ViewHelperPluginManager by adding a factory to getViewHelperConfig.

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);
            }
        ),
    );
}

Now in the view script you can echo the system name using the helper.

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

You can also use other view helpers within you new helper; so you could get the escapeHtml helper and escape HTML content within the getName() method (I'll leave that to you).