phpzend-frameworkzend-form

Problem with binding an object in the form with Zend Framework


I'm doing the tutorial of Zend Framework from this link : https://docs.zendframework.com/tutorials/getting-started/forms-and-actions/#editing-an-album

I reach this part without any problems, but now I'm raising this error :

Argument 1 passed to Zend\Hydrator\ArraySerializableHydrator::extract() must be an instance of Zend\Hydrator\object, instance of Album\Model\Album given, called in /client/zf3/skeleton/vendor/zendframework/zend-form/src/Fieldset.php on line 650

I have the same code as in the tutorial, and I looked into internet for another problem like this one, unfortunately I found none.

Is there a new way to use the Hydrator (compared to the tutorial) ? Or I made a mistake which I'm not able to find ?

module/Album/src/Model/Album.php:

<?php
namespace Album\Model;

use DomainException;
use Zend\Filter\StringTrim;
use Zend\Filter\StripTags;
use Zend\Filter\ToInt;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFIlterInterface;
use Zend\Validator\StringLength;

class Album implements InputFilterAwareInterface{
  public $id;
  public $artist;
  public $title;

  private $inputFilter;

  public function exchangeArray(array $data){
    $this->id = !empty($data['id']) ? $data['id'] : null;
    $this->artist = !empty($data['artist']) ? $data['artist'] : null;
    $this->title = !empty($data['title']) ? $data['title'] : null;
  }

  public function getArrayCopy(){
    return [
      'id' => $this->id,
      'artist' => $this->artist,
      'title' => $this->title,
    ];
  }

  public function setInputFilter(InputFilterInterface $inputFilter){
    throw new DomainException(sprintf('%s does not allow injection of an alternate input filter', __CLASS__));
  }

  public function getInputFilter(){
    if($this->inputFilter){
      return $this->inputFilter;
    }

    $inputFilter = new InputFilter();

    $inputFilter->add([
      'name' =>'id',
      'required' => true,
      'filters' => [
        ['name' => ToInt::class],
      ],
    ]);

    $inputFilter->add([
      'name' =>'artist',
      'required' => true,
      'filters' => [
        ['name' => StripTags::class],
        ['name' => StringTrim::class],
      ],
      'validators' => [
        [
          'name' => StringLength::class,
          'options' => [
            'encoding' => 'UTF-8',
            'min' => 1,
            'max' => 100,
          ],
        ],
      ],
    ]);

    $inputFilter->add([
      'name' => 'title',
      'required' => true,
      'filters' => [
        ['name' => StripTags::class],
        ['name' => StringTrim::class],
      ],
      'validators' => [
        [
            'name' => StringLength::class,
            'options' => [
            'encoding' => 'UTF-8',
            'min' => 1,
            'max' => 100,
          ],
        ],
      ],
    ]);

    $this->inputFilter = $inputFilter;
    return $this->inputFilter;
  }
}

module/Album/src/Controller/AlbumController.php:

<?php

namespace Album\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Album\Model\AlbumTable;
use Album\Form\AlbumForm;
use Album\Model\Album;

class AlbumController extends AbstractActionController{

  private $table;

  public function __construct(AlbumTable $table){
    $this->table = $table;
  }

  public function indexAction(){
    return new ViewModel([
      'albums' => $this->table->fetchAll(),
    ]);
  }

  public function addAction(){
    $form = new AlbumForm();
    $form->get('submit')->setValue('Add');

    $request = $this->getRequest();

    if(!$request->isPost()){
      return ['form' => $form];
    }

    $album = new Album();
    $form->setInputFilter($album->getInputFilter());
    $form->setData($request->getPost());

    if(! $form->isValid()){
      return ['form' => $form];
    }

    $album->exchangeArray($form->getData());
    $this->table->saveAlbum($album);
    return $this->redirect()->toRoute('album');
  }

  public function editAction(){
    $id = (int) $this->params()->fromRoute('id',0);

    if(0 === $id){
      return $this->redirect()->toRoute('album',['action' => 'index']);
    }

    try{
      $album = $this->table->getAlbum($id);
    } catch (\Exception $e){
     return $this->redirect()->toRoute('album', ['action' => 'index']);
    }
    var_dump($album);
    $form = new AlbumForm();
    $form->bind($album);
    $form->get('submit')->setAttribute('value','Edit');

    $request = $this->getRequest();
    $viewData = ['id' => $id, 'form' => $form];

    if(! $request->isPost()){
      return $viewData;
    }

    $form->setInputFilter($album->getInputFilter());
    $form->setData($request->getPost());

    if(! $form->isValid()){
      return $viewData;
    }

    $this->table->saveAlbum($album);

    return $this->redirect()->toRoute('album', ['action' => 'index']);
  }

  public function deleteAction(){

  }
}

module/Album/src/Form/AlbumForm.php

<?php
namespace Album\Form;

use Zend\Form\Form;

class AlbumForm extends Form {
  public function __construct($name = null){
    parent::__construct('album');

  $this->add([
    'name' => 'id',
    'type' => 'hidden',
  ]);
  $this->add([
    'name' => 'title',
    'type' => 'text',
    'options' => [
      'label' => 'Title',
    ],
  ]);
  $this->add([
    'name' => 'artist',
    'type' => 'text',
    'options' => [
      'label' => 'Artist',
    ],
  ]);
  $this->add([
    'name' => 'submit',
    'type' => 'submit',
    'attributes' => [
      'value' => 'Go',
      'id' => 'submitbutton',
    ],
  ]);
  }
}

Thanks for your help !


Solution

  • After some research, I still haven't found how to solve the problem with Hydrator. But I found another solution, here it is.

    In module/Album/src/Controller/AlbumController.php

    public function editAction(){
        $id = (int) $this->params()->fromRoute('id',0);
    
        if(0 === $id){
          return $this->redirect()->toRoute('album',['action' => 'index']);
        }
    
        try{
          $album = $this->table->getAlbum($id);
        } catch (\Exception $e){
         return $this->redirect()->toRoute('album', ['action' => 'index']);
        }
    
        $form = new AlbumForm();
        $form->setData($album->getArrayCopy());//Here is the change instead of bind
        $form->get('submit')->setAttribute('value','Edit');
    
        //Here to save the modifications
        $request = $this->getRequest();
        $viewData = ['id' => $id, 'form' => $form];
        if($request->isPost()){
          $form->setData($request->getPost());
          if($form->isValid()){
            $data = $form->getData();
            $album->exchangeArray($data);
            $this->table->saveAlbum($album);
    
            return $this->redirect()->toRoute('album', ['action' => 'index']);
          }
        }
    
        return $viewData;
      }
    

    I know it's not perfect but it's better working than no working. Hope it can help someone someday. ;)