fork download
  1. <?php
  2. /**
  3.  * Helper for rendering mulpile form array elements.
  4.  * @see http://stackoverflow.com/questions/13157113/zf-form-array-field-how-to-display-values-in-the-view-correctly
  5.  */
  6. class Website_View_Helper_FormArrayElements extends Zend_View_Helper_Abstract
  7. {
  8. private $elements;
  9.  
  10. private $partial;
  11.  
  12. /**
  13. * Creates a helper instance.
  14. * @param array $arrayElements array of elements that are used in the given partial script; they must be an array fields
  15. * @param string $partial script to render for each value in the given form array elements
  16. * @return Website_View_Helper_FormArrayElements
  17. */
  18. public function formArrayElements(array $arrayElements, $partial){
  19. // check some preconditions
  20. if(count($arrayElements) == 0)
  21. throw InvalidArgumentException('Elements array must contain at least one element.');
  22. foreach($arrayElements as $element){
  23. if(!$element instanceof Zend_Form_Element)
  24. throw InvalidArgumentException('Elements of class ' . get_class($element) . ' is not a form element.');
  25. /* @var $element Zend_Form_Element */
  26. if(!$element->isArray())
  27. throw InvalidArgumentException('Element [' . $element->getName() . '] is not an array.');
  28. }
  29. $this->elements = $arrayElements;
  30. $this->partial = $partial;
  31. return $this;
  32. }
  33.  
  34. /**
  35. * Render the fields.
  36. */
  37. public function render(){
  38. $values = array();
  39. // only if the form were submitted we need to validate fields' values
  40. // and display errors next to them; otherwise when user enter the page
  41. // and render the form for the first time - he would see Required validator errors
  42. $needsValidation = false;
  43. foreach($this->elements as $element){
  44. $v = $element->getValue();
  45. if(is_array($v)){
  46. $needsValidation = true;
  47. $values[$element->getName()] = $v;
  48. }
  49. else{
  50. // print empty fields when the form is displayed the first time
  51. $values[$element->getName()] = array('');
  52. }
  53. }
  54. // iterate over all values
  55. $rendered = '';
  56. foreach(array_keys(current($values)) as $valueKey){
  57. $elements = array();
  58. foreach($this->elements as $element){
  59. $currentValue = $values[$element->getName()][$valueKey];
  60. if($needsValidation)
  61. $element->isValid($currentValue);
  62. $elements[$element->getName()] = (string)$element->setValue($currentValue);
  63. }
  64. $rendered .= $this->view->partial($this->partial, $elements);
  65. }
  66. return $rendered;
  67. }
  68.  
  69. public function __toString(){
  70. return $this->render();
  71. }
  72. }
Runtime error #stdin #stdout #stderr 0.01s 20520KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
PHP Fatal error:  Class 'Zend_View_Helper_Abstract' not found in /home/rK3qxF/prog.php on line 7