vendredi 10 avril 2015

ZF2 Passing Route To Form Element

I am creating a form which needs dynamic options based on the route value of survey_question_reference



'main-surveyquestions' => [
'type' => 'segment',
'options' => [
'route' => '/survey-questions[/:survey_question_reference][/:answer]',
'constraints' => [
'survey_question_reference' => '[0-9]*',
'answer' => '(answer)',
],
'defaults' => [
'controller' => 'Main\Controller\Main',
'action' => 'surveyquestions'
]
]
],


This is the Form code which calls the Form Element:



/**
* Init
*/
public function init()
{
/**
* Survey Answer
*/
$this->add(
[
'type' => 'Main\Form\Element\SurveyAnswerRadio',
'name' => 'survey_answer',
'options' => [
'label' => 'survey_answer'
],
'attributes' => [
'id' => 'survey_answer'
]
]
);
}


The following is the code from the Form Element. Where I have hard coded 'sqReference' => '1' the 1 needs to be replaced with the value of survey_question_reference from the route.



namespace Main\Form\Element;

use Doctrine\ORM\EntityManager;
use Zend\Form\Element\Radio;

/**
* Class SurveyAnswerRadio
*
* @package Main\Form\Element
*/
class SurveyAnswerRadio extends Radio
{
/**
* @var EntityManager $entityManager
*/
protected $entityManager;

/**
* @param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}

/**
* Get Value Options
*
* @return array
*
* @throws \Exception
*/
public function getValueOptions()
{
$array = [];

$result = $this->entityManager
->getRepository('AMDatabase\Entity\TheVerse\SA')
->findBy(
[
'sqReference' => '1'
],
[
'surveyAnswer' => 'ASC'
]
);

if (is_array($result) && count($result) > '0') {
/**
* @var \AMDatabase\Entity\TheVerse\SA $val
*/
foreach ($result as $val) {
$array[$val->getReference()] = $val->getSurveyAnswer();
}
}

return $array;
}
}

Aucun commentaire:

Enregistrer un commentaire