Unrecognized field: user_name, while querying Via Doctrine using ZF2 - php

here is the snippet to my code when i try to query it like this
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
//check authentication...
$this->getAuthService()->getAdapter()
->setIdentity($request->getPost('username'))
->setCredential($request->getPost('password'));
$username = $request->getPost('username');
$password = $request->getPost('password');
$result = $this->getAuthService()->authenticate();
$criteria = array("user_name" => $username,);
$results= $this->getEntityManager()->getRepository('Subject\Entity\User')->findBy($criteria);
print_r($results);
exit;
i get the following error
Unrecognized field: user_name
These are my includes
Use Doctrine\ORM\EntityManager,
Album\Entity\Album;
Edit: this is my Subject\Entity\User file
<?php
namespace Subject\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
/**
* #ORM\Entity
* #ORM\Table(name="users")
* #property string $username
* #property string $password
* #property int $id
*/
class User implements InputFilterAwareInterface {
protected $_username;
protected $_password;
/**
* #ORM\OneToMany(targetEntity="Subject\Entity\Subject", mappedBy="user")
* #var Collection
*/
private $subjects;
/** #ORM\Id() #ORM\Column(type="integer") #ORM\GeneratedValue(strategy="AUTO") #var int */
protected $_id;
public function __get($property) {
return $this->$property;
}
public function __set($property, $value) {
$this->$property = $value;
}
//Getters and setters
/** #return Collection */
public function getSubjects() {
return $this->subjects;
}
/** #param Comment $comment */
public function addSubject(Subject $subjects) {
$this->subjects->add($subjects);
$subjects->setUser($this);
}
public function __construct($subjects) {
//Initializing collection. Doctrine recognizes Collections, not arrays!
$this->subjects = new ArrayCollection();
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function populate($data = array()) {
$this->_id = $data['id'];
$this->_username = $data['username'];
$this->_password = $data['password'];
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception("Not used");
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
//put your code here
}
?>

You are querying for the wrong field. The field is named _username in your entity class. Also check you annotations, _username and _password seem to not have any so they won't be created as database fields.
If you set up your entity correctly and all fields are in database you just need to query for your _username property:
if ($request->isPost()) {
$form->setData($request->getPost());
$repo = $this->getEntityManager()->getRepository('Subject\Entity\User');
if ($form->isValid()) {
// snip ...
$criteria = array("_username" => $username,);
$results= $repo->findBy($criteria);
print_r($results);
exit;
}
}
You user entity should look something like:
class User implements InputFilterAwareInterface {
/**
* #ORM\Column(name="username", type="string", length=64, unique=true)
*/
protected $_username;
/**
* #ORM\Column(name="password", type="string", length=64)
*/
protected $_password;
// snip ...
}
You may take a look at the PSR-2 standards. Underscores in method and variable names are discouraged by now.

Related

ZF2 and Doctrine 2: Translation entity form

I need to create ZF2 form for a Doctrine translatable Entity (I use https://github.com/Atlantic18/DoctrineExtensions Translatable Extension), which should provide fields for all translatable properties(columns) of the entity in each available language.
So far I have the following:
1) Article Entity
namespace TestModule\Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Doctrine\ORM\Mapping\Entity(repositoryClass="TestModule\Entity\ArticleRepository")
* #Doctrine\ORM\Mapping\Table(name="test_module_articles")
* #Gedmo\Mapping\Annotation\TranslationEntity(class="TestModule\Entity\ArticleTranslation")
*/
class Article
{
/**
* #var int Auto-Incremented Primary Key
*
* #Doctrine\ORM\Mapping\Id
* #Doctrine\ORM\Mapping\Column(type="integer")
* #Doctrine\ORM\Mapping\GeneratedValue
*/
protected $id;
/**
* #Doctrine\ORM\Mapping\Column(type="string")
* #Gedmo\Mapping\Annotation\Translatable
*/
protected $name;
/**
* #Doctrine\ORM\Mapping\Column(type="text", length=65535)
* #Gedmo\Mapping\Annotation\Translatable
*/
protected $description;
/**
* #Gedmo\Mapping\Annotation\Locale
* Used locale to override Translation listener`s locale
* this is not a mapped field of entity metadata, just a simple property
* and it is not necessary because globally locale can be set in listener
*/
private $locale;
/**
* #Doctrine\ORM\Mapping\OneToMany(
* targetEntity="TestModule\Entity\ArticleTranslation",
* mappedBy="object",
* cascade={"persist", "remove"}
* )
*/
private $translations;
public function __construct()
{
$this->translations = new ArrayCollection();
}
public function getTranslations()
{
return $this->translations;
}
public function addTranslation(\TestModule\Entity\ArticleTranslation $t)
{
if (!$this->translations->contains($t)) {
$this->translations[] = $t;
$t->setObject($this);
}
}
public function addTranslations($translations)
{
foreach ($translations as $translation) {
$this->addTranslation($translation);
}
}
public function removeTranslations($translations)
{
foreach ($translations as $translation) {
$this->translations->removeElement($translation);
$translation->setObject(null);
}
}
public function setTranslatableLocale($locale)
{
$this->locale = $locale;
}
}
2) ArticleTranslation Entity
namespace TestModule\Entity;
use Gedmo\Translatable\Entity\MappedSuperclass\AbstractPersonalTranslation;
/**
* #Doctrine\ORM\Mapping\Entity
* #Doctrine\ORM\Mapping\Table(name="test_module_articles_translations",
* uniqueConstraints={#Doctrine\ORM\Mapping\UniqueConstraint(name="lookup_unique_idx", columns={
* "locale", "object_id", "field"
* })}
* )
*/
class ArticleTranslation extends AbstractPersonalTranslation
{
/**
* Convinient constructor
*
* #param string $locale
* #param string $field
* #param string $value
*/
public function __construct($locale, $field, $value)
{
$this->setLocale($locale);
$this->setField($field);
$this->setContent($value);
}
/**
* #Doctrine\ORM\Mapping\ManyToOne(targetEntity="TestModule\Entity\Article", inversedBy="translations")
* #Doctrine\ORM\Mapping\JoinColumn(name="object_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $object;
}
3) The Form
namespace TestModule\Form;
use Zend\Form\Form;
use Doctrine\ORM\EntityManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use TestModule\Form\ArticleTranslationsFieldset;
use TestModule\Entity\ArticleTranslation;
class ArticleForm extends Form
{
protected $entityManager;
public function __construct(EntityManager $entityManager,$name = null)
{
parent::__construct($name);
$this->entityManager = $entityManager;
$hydrator = new DoctrineHydrator($this->entityManager, 'TestModule\Entity\Article');
$this->setAttribute('method', 'post')
->setHydrator($hydrator)
//->setInputFilter($inputFilter)
;
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$articleFieldset = new ArticleTranslationsFieldset($entityManager);
$fieldsetHydrator = new DoctrineHydrator($entityManager, 'TestModule\Entity\ArticleTranslation');
$articleFieldset->setHydrator($fieldsetHydrator)->setObject(new ArticleTranslation('en','name',''));
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'translations',
'allow_empty' => true,
'options' => array(
'label' => '',
'count' => 0,
'allow_add' => true,
'allow_remove' => true,
'target_element' => $articleFieldset,
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Submit'
),
));
}
}
4) And the Translations Fieldset:
namespace TestModule\Form;
use Zend\Form\Fieldset;
class ArticleTranslationsFieldset extends Fieldset
{
public function __construct()
{
parent::__construct('translations');
$this->add(array(
'name' => 'locale',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'field',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'content',
'type' => 'Zend\Form\Element\Text',
'options' => array(
'label' => _(''),
),
'attributes' => array(
'type' => 'text',
),
));
}
}
With this set-up I can save both the name and the description properties for each language, but I cannot manage the content field type - it is Text element for either the name and the description and cannot set the proper field label. I also cannot group the elements by language so that the form presented to the user is well organized.
Do you have any other suggestions how to solve this problem?
What I want to achieve is something like this:
I couldn't find a solution with the Translatable Doctrine Extension that I used in the question. So I search for another one and finally I end up using the Prezent Extension(https://github.com/Prezent/doctrine-translatable).
With this extension the translation entity contains the translatable fields, which makes it easy to map the translation entity with the translations fieldset. Each translation entity has a locale property which I map to a hidden field in the fieldset and use it to present the form in the desired way.

Php Dependency Injecttion in Zend 2

I have two classes. Lets says it is Album and AlbumManager. Album is a intake class which I am using for generating basic entity function. I do not want to touch Album for custom functions. All other custom function I wrote in AlbumManager class.
Now from controller, when I try to access Album class through AlbumManager, it through me an error:
Can not be mapped or accessed.
How can I handle this type of dependency? Here are the classes:
Album.php
<?php
namespace Album\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Album
*
* #ORM\Table(name="album")
* #ORM\Entity
*/
class Album
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="artist", type="string", length=255, precision=0, scale=0, nullable=false, unique=false)
*/
private $artist;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set artist
*
* #param string $artist
* #return Album
*/
public function setArtist($artist)
{
$this->artist = $artist;
return $this;
}
/**
* Get artist
*
* #return string
*/
public function getArtist()
{
return $this->artist;
}
?>
AlbumManager.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace Album\Manager;
use Album\Entity as Album;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterInterface;
class AlbumManager
{
private $album;
protected $inputFilter;
public function __construct(Album\Entity $album)
{
$this->album = $album;
}
public function getAlbum()
{
return $this->album;
}
/**
* Magic getter to expose protected properties.
*
* #param string $property
* #return mixed
*/
public function __get($property)
{
return $this->$property;
}
/**
* Magic setter to save protected properties.
*
* #param string $property
* #param mixed $value
*/
public function __set($property, $value)
{
$this->$property = $value;
}
/**
* Convert the object to an array.
*
* #return array
*/
public function getArrayCopy()
{
return get_object_vars($this);
}
/**
* Populate from an array.
*
* #param array $data
*/
public function populate($data = array())
{
$this->album->setId($data['id']);
$this->album->setArtist($data['artist']);
$this->album->setTitle($data['title']);
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'artist',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'title',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
AlbumController.php
<?php
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController,
Zend\View\Model\ViewModel,
Album\Form\AlbumForm,
Doctrine\ORM\EntityManager,
Doctrine\ORM\EntityRepository,
Album\Entity\Album,
Album\Manager\AlbumManager,
class AlbumController extends AbstractActionController
{
public function addAction()
{
$form = new AlbumForm();
$form->get('submit')->setAttribute('label', 'Add');
$request = $this->getRequest();
if ($request->isPost()) {
$album = new Album();
$albumManager = new AlbumManager($album);
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$album->populate($form->getData());
$this->getEntityManager()->persist($album);
$this->getEntityManager()->flush();
// Redirect to list of albums
return $this->redirect()->toRoute('album');
}
}
return array('form' => $form);
}
?>
See the code at AlbumController
$album = new Album();
$albumManager = new AlbumManager($album);
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$album->populate($form->getData());
The album object can not get access to the getInputFilter and populate function which I write down in the Album Repository. I understood this happened because of the dependency injected. But what would be the solution so that I can access the album object, set the form data and also can use the album manger functions?

Can't validate my form in Zend Framework 2

So I create a form and I want to use it in my project. I use Zend Framework 2 and Doctrine Orm. The problem occurs when I submit the form: I had nothing, that means the form wasn't submitted. For more details I will write my code. So if someone has any solution I will be very appreciative.
This is my entity :
class Article implements InputFilterAwareInterface
{
protected $inputFilter;
/**
* #ORM\Column(name="publication", type="boolean")
*/
protected $publication;
public function __construct()
{
$this->date = new \Datetime();
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
protected $title;
// ....
/**
* Populate from an array.
*
* #param array $data
*/
// here maybe the data can't pass from my form to the entity !!
public function populate($data = array())
{
$this->content = $data['content'];
$this->title = $data['title'];
$this->date = $data['date'];
$this->publication = $data['publication'];
$this->image = $data['image'];
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'content',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 60,
),
),
),
)));
// ....
}
}
Then my Action:
$form = new ArticleForm();
$form->get('submit')->setAttribute('label', 'Add');
$request = $this->getRequest();
if ($this->zfcUserAuthentication()->hasIdentity()) {
if ($request->isPost())
{
$article = new Article();
$form->setInputFilter($article->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$article->populate($form->getData());// here i think i have a problem
$this->getObjectManager()->flush();
$newId = $article->getId();
return $this->redirect()->toRoute('blog');
}
}
}
instead of : $article->populate($form->getData());
try: $article->populate($request->getPost()->toArray());//bad idea
or : $article->populate($form->getData()->toArray());//good idea
up:
$form->getData() will return entity so you must implement toArray() function;
public function toArray()
{
return array(
'title' => $this->title,
//...
);
}

form not binding post values to entity

I have a doctrine entity, a form and 2 fieldsets.
When i populate the entity with values the values get hydrated into the form as expected.
When i try to create a entity from form data it stays empty..
i must be forgetting something but just cant find it, i have several other forms without fieldsets and they work as expected.
any ideas?
posted my code below
Entity:
class User
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=255, unique=true, nullable=true)
*/
protected $username;
..
}
Form:
class CreateUserForm extends Form
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('create-user');
$this->setAttribute('method', 'post');
// The form will hydrate an object
$this->setHydrator(new DoctrineHydrator($objectManager));
$userFieldset = new UserFieldset($objectManager);
$this->add($userFieldset);
// … add CSRF and submit elements …
$baseFieldset = new BaseFieldset($objectManager);
$baseFieldset->setUseAsBaseFieldset(true);
$this->add($baseFieldset);
}
}
UserFIeldset:
class UserFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($objectManager)
{
parent::__construct($name = 'user');
$this->setHydrator(
new DoctrineHydrator($objectManager, 'YrmUser\Entity\User')
)->setObject(new User());
$this->add(
array(
'name' => 'username',
'attributes' => array(
'type' => 'text',
'placeholder' =>'Username',
),
'options' => array(
'label' => 'Username',
),
)
);
...
}
}
BaseFieldset:
class BaseFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($objectManager)
{
parent::__construct('base');
$this->setHydrator(new DoctrineHydrator($objectManager));
$this->add(
array(
'name' => 'security',
'type' => 'Zend\Form\Element\Csrf',
'options' => array(
'csrf_options' => array(
'timeout' => 600
)
)
)
);
$this->add(
array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Save',
'class' => 'btn btn-success btn-lg confirm',
),
)
);
}
}
controller action:
public function createAction()
{
$form = new CreateUserForm($this->getObjectManager());
$entity = new User();
$form->bind($entity);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getObjectManager()->persist($entity);
$this->getObjectManager()->flush();
return $this->redirect()->toRoute($this->redirect);
}
}
return array(
'form' => $form
);
}
Can you var_dump $form->getData() after $form->isValid() ?
Alternatively, you can try $form->isValid($request->getPost()) instead of setData().

ZF2: FieldSet getInputFilterSpecification() gets called twice

getInputFilterSpecification() read twice for a fieldset when used with fileprg Controller plugin.
Basically I have a simple form with a single fieldset:
The Form:
class CreateEditReward extends ProvideEventsForm
{
public function __construct($name = null, $options = array())
{
parent::__construct($name ?: 'Reward', $options);
$this->add(array(
'name' => 'submit',
'type' => 'submit'
));
$this->add(array(
'name' => 'cancel',
'type' => 'button'
));
}
public function init()
{
parent::init();
$this->add(array(
'name' => 'reward',
'type' => 'MyAchievement\Form\RewardFieldset',
'options' => array(
'use_as_base_fieldset' => true
)
));
if (($listener = $this->get('reward')) instanceof ListenerAggregateInterface) {
/** #var $listener ListenerAggregateInterface */
$this->getEventManager()->attachAggregate($listener);
}
}
}
The form extends the most basic EventsCapable implmentation and is not related to the problem.
The Fieldset:
class RewardFieldset extends Fieldset implements
InputFilterProviderInterface,
ListenerAggregateInterface
{
/**
* #var RewardService
*/
protected $rewardService;
/**
* #var WebPathResolver
*/
protected $webPathResolver;
protected $listeners = array();
public function __construct(RewardService $rewardService, WebPathResolver $webPathResolver, $name = null, $options = array())
{
parent::__construct($name ?: 'Reward', $options);
$this->rewardService = $rewardService;
$this->webPathResolver = $webPathResolver;
//...
$this->add(array(
'name' => 'thumb',
'type' => 'file',
'options' => array(
'label' => 'Thumb'
),
'attributes' => array(
'id' => 'thumb',
'data-rel' => null
)
));
// .. more elts
}
/**
* Should return an array specification compatible with
* {#link Zend\InputFilter\Factory::createInputFilter()}.
*
* #return array
*/
public function getInputFilterSpecification()
{
return array(
// ... other elts input filters
'thumb' => array(
'required' => false,
'filters' => array(
array(
'name' => 'fileRenameUpload',
'options' => array(
'target' => './data/upload',
'overwrite' => true,
'randomize' => true,
'use_upload_name' => true
)
)
),
'validators' => array(
array(
'name' => 'fileMimeType',
'options' => array(
'image',
'enableHeaderCheck' => true
)
)
)
)
);
}
public function addThumbPreview(FormEvent $e)
{
/** #var $object Reward */
if (! ($object = $e->getObject()) instanceof Reward) {
return;
}
if ($object->getThumb()) {
$this->get('thumb')
->setAttribute('data-rel', $this->webPathResolver->getPath($object, $object->getThumb()));
}
}
/**
* Attach one or more listeners
*
* Implementors may add an optional $priority argument; the Eve\ntManager
* implementation will pass this to the aggregate.
*
* #param EventManagerInterface $events
*
* #return void
*/
public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach(FormEvent::EVENT_POST_BIND, array($this, 'addThumbPreview'));
}
/**
* Detach all previously attached listeners
*
* #param EventManagerInterface $events
*
* #return void
*/
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $i => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$i]);
}
}
}
}
My controller's edit action:
public function editAction()
{
/** #var $request Request */
$request = $this->getRequest();
$back = $request->getQuery('back', $this->url()->fromRoute('admin/reward'));
/** #var $reward Reward */
if (null === $reward = $this->rewardService->fetchById($id = $this->params()->fromRoute('id'))) {
return $this->redirect()->toUrl($back);
}
$form = $this->getCreateEditForm();
$form->bind($reward);
if (($prg = $this->fileprg($form)) instanceof ResponseInterface) {
return $prg;
}
if (is_array($prg)) {
try {
if ($form->isValid()) {
$this->rewardService->updateReward($reward);
$this->flashMessenger()->addSuccessMessage('Changes saved');
$this->redirect()->toRoute('admin/reward',
array('action' => 'edit', 'id' => $id),
array('query' => array('back' => $back)));
} else {
/** #var $rewardFieldset FieldsetInterface */
$rewardFieldset = $form->get('reward');
/** #var $thumbElt ElementInterface */
$thumbElt = $rewardFieldset->get('thumb');
if (! $thumbElt->getMessages()) {
$reward->setThumb($thumbElt->getValue());
$this->rewardService->updateReward($reward);
}
}
} catch (\Exception $e) {
$this->flashMessenger()->addErrorMessage('Changes could not be saved');
return $this->redirect()->toUrl($back);
}
}
return new ViewModel(array(
'form' => $form,
'reward' => $reward,
'back' => $back
));
}
My module conf for the form:
/**
* Expected to return \Zend\ServiceManager\Config object or array to
* seed such an object.
*
* #return array|\Zend\ServiceManager\Config
*/
public function getFormElementConfig()
{
return array(
'invokables' => array(
'MyAchievement\Form\CreateEditReward' => 'MyAchievement\Form\CreateEditReward',
),
'factories' => array(
'MyAchievement\Form\RewardFieldset' => function (FormElementManager $fm) {
/** #var $rewardService RewardService */
$rewardService = $fm->getServiceLocator()->get('MyAchievement\Service\Reward');
/** #var $webPathResolver WebPathResolver */
$webPathResolver = $fm->getServiceLocator()->get('Application\Service\WebPathResolver');
$fieldset = new RewardFieldset($rewardService, $webPathResolver);
$fieldset->setHydrator(new ClassMethods());
return $fieldset;
}
)
);
}
The problem is the getInputFilterSpecifications() is called twice, thus everytime I try to upload a picture with my form I get
Zend\Filter\Exception\RuntimeException:
File './data/upload/my-thumb_5249d42bd582b.jpg' could not be renamed. An error occurred while processing the file.
That is because my filters run twice on the same thumbnail, the first time it is successful (I can even see the file uploaded to the temp dir).
Thanks.

Categories