zendframework 2 Doctrine 2 my post form is not returning the values - forms

i am a little baffled by this;
my post forms is not populating the values received from the returned post values; i suspect the problem is arising from my getJobId() in my jobsort class values;
below is my form:
public function jobSortAction()
{
$form = new CreateJobSortForm($this->getEntityManager());
$jobSort = new JobSort();
$form->setInputFilter($jobSort->getInputFilter());
$id= 11;
$jobSort->setId($id);
$form->bind($jobSort);
if ($this->request->isPost()) {
//$post = $this->request->getPost();
$form->setData($this->request->getPost());
//var_dump($post);
//var_dump($jobSort);
if ($form->isValid()) {
$this->getEntityManager()->persist($jobSort);
$this->getEntityManager()->flush();
}
}
return array('form' => $form);
}
below is the var_dumped values of the 'return post values' and the Jobsort() object. You will note that the returned post values has values for both the Id and the JobId
object(Zend\Stdlib\Parameters)[168]
public 'JobSort' =>
array (size=2)
'jobId' => string '5' (length=1)
'id' => string '11' (length=2)
public 'submit' => string 'Submit' (length=6)
object(Workers\Entity\JobSort)[394]
protected 'inputFilter' => null
protected 'id' => int 11
protected 'jobId' => null
protected 'workerservicelist' => null
yet, when i populate the values, it does not seem to record the values for the jobId
below is my jobsort entity class:
class JobSort
{
protected $inputFilter;
/**
* #ORM\Id
*
* #ORM\Column(name="user_id", type="integer")
*/
protected $id;
/**
* #ORM\Column(name="jobId", type="integer")
*/
protected $jobId;
public function setId($id)
{
return $this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setJobId($jobId)
{
return $this->jobId = $jobId;
}
public function getJobId( )
{
return $this->jobId;
}
is there any advice or suggestions on what i need to do to find out why the values are not been populated
warm regards
Andreea
by the way; the form actually works when i had the Id of CLASS jobsort set to
#ORM\GeneratedValue(strategy="AUTO")
the problem started when i took it out and set it to manual
Hello again
here is my form:
this is the error message i received;
An exception occurred while executing 'INSERT INTO worker_main_jobsort (user_id, jobId) VALUES (?, ?)' with params [11, null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'jobId' cannot be null
here is my form:
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Form;
use Workers\Form\Fieldset\JobSortFieldset;
class CreateJobSortForm extends Form
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('create-Job-post-form');
// The form will hydrate an object of type "BlogPost"
$this->setHydrator(new DoctrineHydrator($objectManager, 'Workers\Entity\JobSort'));
// Add the user fieldset, and set it as the base fieldset
$JobSortFieldset = new JobSortFieldset($objectManager);
$JobSortFieldset->setUseAsBaseFieldset(true);
$this->add($JobSortFieldset);
// Optionally set your validation group here
// … add CSRF and submit elements …
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Submit',
'id' => 'submitbutton',
),
));
// Optionally set your validation group here
}
}
and here is the fieldset class:
class JobSortFieldset extends Fieldset
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('JobSort');
$id= 10;
$this->setHydrator(new DoctrineHydrator($objectManager, 'Workers\Entity\JobSort'))
->setObject(new JobSort());
}
}
this addition is in response to rafaame solution;
i amended my form as recommended; however it still not working. i think the issue now is that Rafaame solution is in regarding to zendDB save method, but i am using doctrine persis**t and **flush method . i accordingly get the following error message;
Call to undefined method Workers\Entity\JobSort::save()
below is my amended form:
public function jobSortAction()
{
$form = new CreateJobSortForm($this->getEntityManager() );
$jobSort = new JobSort();
if($this->request->isPost())
{
$form->setData($this->request->getPost());
if ($form->isValid())
{
$entity = $form->getData();
$model = new JobSort();
$model->save($entity);
// $this->getEntityManager()->persist( $model);
// $this->getEntityManager()->flush();
}
}
return array('form' => $form);
}
in response to Rafaame question about what problems i had,the message that i am now receiving is this:
**
EntityManager#persist() expects parameter 1 to be an entity object,
array given.
**
below is my function:
public function jobSortAction()
{
$serviceLocator = $this->getServiceLocator();
$objectManager = $this->getEntityManager();
$form = new CreateJobSortForm($this->getEntityManager());
if ($this->request->isPost())
{
$form->setData($this->request->getPost());
if ($form->isValid()) {
$entity = $form->getData();
$model = new JobSort($objectManager, $serviceLocator);
$model->getEntityManager()->persist($entity);
$model->getEntityManager()->flush();
}
}
return array('form' => $form);
}
my form; i.e where the hydrator should be set
namespace Workers\Form;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Form;
use Workers\Form\Fieldset\JobSortFieldset;
class CreateJobSortForm extends Form
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('JobSort');
// The form will hydrate an object of type "BlogPost"
$this->setHydrator(new DoctrineHydrator($objectManager, 'Workers\Entity\JobSort'));
// Add the user fieldset, and set it as the base fieldset
$JobSortFieldset = new JobSortFieldset($objectManager);
$JobSortFieldset->setUseAsBaseFieldset(true);
$this->add($JobSortFieldset);

If you check your code, you are creating a JobSort entity, setting only its id and binding it to the form:
$jobSort = new JobSort();
$jobSort->setId($id);
$form->bind($jobSort);
After that, you are dumping $jobSort and $this->request->getPost(). So, obviously, you are getting jobId in the POST data but not in the entity (you didn't set the entity's jobId before binding it to the form). There's nothing wrong with your entity's code.
The solution for this: don't bind anything to the form. You should only bind an entity to the form in the case of an edit action, that you fetch the entity from the database and want to populate the form with its values.
Example of add action:
public function addAction()
{
$serviceLocator = $this->getServiceLocator();
$objectManager = $this->getObjectManager();
$form = new Form\EmailCampaign\Add($serviceLocator, $objectManager);
if($this->request instanceof HttpRequest && $this->request->isPost())
{
$form->setData($this->request->getPost());
if($form->isValid())
{
$entity = $form->getData();
//If you want to modify a property of the entity (but remember that it's not recommended to do it here, do it in the model instead).
//$entity->setJobId(11);
$model = new Model\EmailCampaign($serviceLocator, $objectManager);
$model->save($entity);
if($entity->getId())
{
$this->flashMessenger()->addSuccessMessage('Email campaign successfully added to the database.');
return $this->redirect()->toRoute('admin/wildcard', ['controller' => 'email-campaign', 'action' => 'edit', 'id' => $entity->getId()]);
}
else
{
$this->flashMessenger()->addErrorMessage('There was an error adding the email campaign to the database. Contact the administrator.');
}
}
}
return new ViewModel
([
'form' => $form,
]);
}
Example of edit action:
public function editAction()
{
$serviceLocator = $this->getServiceLocator();
$objectManager = $this->getObjectManager();
$form = new Form\EmailCampaign\Edit($serviceLocator, $objectManager);
$id = $this->getEvent()->getRouteMatch()->getParam('id');
$entity = $objectManager
->getRepository('Application\Entity\EmailCampaign')
->findOneBy(['id' => $id]);
if($entity)
{
$form->bind($entity);
if($this->request instanceof HttpRequest && $this->request->isPost())
{
$form->setData($this->request->getPost());
if($form->isValid())
{
//If you want to modify a property of the entity (but remember that it's not recommended to do it here, do it in the model instead).
//$entity->setJobId(11);
$model = new Model\EmailCampaign($serviceLocator, $objectManager);
$model->save($entity);
$this->flashMessenger()->addSuccessMessage('Email campaign successfully saved to the database.');
}
}
}
else
{
$this->flashMessenger()->addErrorMessage('A email campaign with this ID was not found in the database.');
return $this->redirect()->toRoute('admin', ['controller' => 'email-campaign']);
}
return new ViewModel
([
'form' => $form,
'entity' => $entity,
]);
}
Hope this helps.
EDIT:
What I provided was an example of how to handle the form and the entities with Doctrine 2 + ZF2.
What you have to keep in mind is that Doctrine doesn't work with the concept of models, it just understands entities. The model I'm using in my application is a concept of the MVC (Model-View-Controller) design pattern (that ZF2 uses) and I have decided to wrap the entity manager calls (persist and flush) inside my model's method, that I named save() (in the case the entity needs some special treatment before being save to the database and also because it is not a good practice to use the entity manager directly in the controller - see this slide of Marcos Pivetta presentation http://ocramius.github.io/presentations/doctrine2-zf2-introduction/#/66).
Another thing that you may be misunderstanding is that when you do $form->getData() to a form that has the DoctrineObject hydrator, it will return you the entity object, and not an array with the data (this last happens if it has no hydrator). So you don't need to create the entity after doing $form->getData(), and if you do so, this created entity won't have any information provided by the form.
Your code should work now:
public function jobSortAction()
{
$serviceLocator = $this->getServiceLocator();
$entityManager = $this->getEntityManager();
$form = new CreateJobSortForm($entityManager);
if ($this->request->isPost())
{
$form->setData($this->request->getPost());
if ($form->isValid()) {
//I'm considering you are setting the DoctrineObject hydrator to your form,
//so here we will get the entity object already filled with the form data that came through POST.
$entity = $form->getData();
//Again, if you need special treatment to any data of your entity,
//you should do it here (well, I do it inside my model's save() method).
//$entity->setJobId(11);
$entityManager->persist($entity);
$entityManager->flush();
}
}
return array('form' => $form);
}

Related

How to pass variable from postPersist Event listener to Controller

I have implemented an EventListener class and declare it in services.yaml
I'd like to return to my Controller a variable when entity is persited and send this variable to twig template. I want to show a step form in my view showing Entity name in green for example when data has been persisted in database. If it works I will use the same process in another controller where I persist multiple entities. To sum up: How to notify a controller that a specific entity has been persisted by passing a variable?
The eventlistener
<?php
namespace App\EventListener;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use App\Entity\Article;
class TodoListener {
public function postPersist(LifecycleEventArgs $args) {
$entity = $args->getObject();
if(!$entity instanceof Article)
return;
$var = 'foo';
return $var;
}
}
services.yaml
App\EventListener\TodoListener:
tags:
- { name: doctrine.event_listener, event: postPersist }
Controller
/**
* #Route("/blog/new", name="blog_create")
* #Route("/blog/{id}/edit", name="blog_edit")
*/
public function form(Article $article = null, Request $request, ObjectManager $manager)
{
if (!$article) {
$article = new Article();
}
$form = $this->createForm(ArticleType::class, $article);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if (!$article->getId()) {
$article->setCreatedAt(new \dateTime());
}
$manager->persist($article);
$manager->flush();
/**
* Get back variable when entity is persisted ???
*/
return $this->redirectToRoute('blog_show', ['id' => $article->getId()]);
}
return $this->render('blog/create.html.twig', [
'formArticle' => $form->createView(),
'editMode' => $article->getId() !== null
]);
}
In short: you can’t.
You can try to work around it with a custom symfony event, but is very bad.
If you want to know if an entity is new or already persisted you should call getEntityState on entity manager’s UnitOfWork or split the flows between actions (write two distinct actions for new and edit).
Anyway, just a suggestion: set the createdAt field into the entity constructor ;)

Symfony 5 dynamic form conditional default logic

I've an use case where i need some default conditional logic on my dynamic form build in Symfony 5.
Let me try to explain what my use case is and my problem with a simple form.
For example i've a form Product with two fields:
Part (choiceType => left, right)
Length (numberType)
On change all fields (:input) are being submitted through an Ajax request.
I've two controller methods one for visiting the page (form is being build), the other
is being called for rendering the form through the ajax request (handle conditional logic).
For the conditional logic part the following needs te be done
When part is left, default length needs to be 50
When part is right, default length needs to be 100
user could change default data
Setting the default data on length based on left or right is not the problem.
When left is selected, default length becomes 50. When changing the value to 55 (form is being submitted through every change) it becomes 50 again.
This behaviour is logic, but how could the default data been overwritten?
Above situation could also been described as give user default data with option to change it
form type
<?php
// ... namespace, use statments
class ProductType extends AbstractType
{
/**
* {#inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('part', ChoiceType::class, array(
'choices' => array(
'Left' => 'left',
'Right' => 'right',
)
));
$builder->add('length', NumberType::class);
$builder->addEventListener(FormEvents::POST_SET_DATA, function(FormEvent $event) use ($options)
{
$form = $event->getForm();
if(null === $product = $event->getData()) {
return;
}
switch($product->getPart()) {
case 'left': $defaultLength = 50; break;
case 'right': $defaultLength = 100; break;
default: $defaultLength = 0;
}
$form->get('length')->setData($defaultLength);
});
}
/**
* {#inheritDoc}
*/
public function getName(): string
{
return 'product';
}
/**
* {#inheritDoc}
*/
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(array(
'data_class' => Product::class,
'translation_domain' => 'forms',
));
}
}
controller
// src/Controller/ProductController.php
// ... namespace, use statments
namespace App\Controller;
class ProductController extends AbstractController
{
public function productAction(Request $request): Response
{
$product = new Product();
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$product = $form->getData();
dd($product);
}
return $this->render('product_view.html.twig', array(
'form' => $form->createView()
));
}
public function productConfigureAjaxAction(Request $request): Response
{
$product = new Product();
$part = $request->request->get('product')['part'] ?? null;
$product->setPart($part);
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
// product_form.html.twig is an separated file and included in product_view.html.twig
// by making the form separated is could been used for an ajax response
return $this->render('product_form.html.twig', array(
'form' => $form->createView()
));
}
}

How to set up a zf2 form for a ManyToOne doctrine mapping

I'm having trouble hydrating a form in zf2 using a doctrine ManyToOne unidirectional relationship. My entities look like this:
namespace AdminMyPages\Entity;
class MyPageItem
{
// ...
/**
* #ORM\ManyToOne(targetEntity="MyMessage")
* #ORM\JoinColumn(name="myMessageID", referencedColumnName="myMessageID")
**/
private $myMessage;
// ...
/**
* Set MyMessage
*
* #param Collection $myMessage
*/
public function setMyMessage(Collection $myMessage = null)
{
$this->myMessage = $myMessage;
}
/**
* Get MyMessage
*
* #return myMessage
*/
public function getMyMessage()
{
return $this->myMessage;
}
}
class MyMessage
{
// ...
}
The fieldset for MyPageItemFieldset looks like this:
namespace AdminMyPages\Form;
class MyPageItemFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('mypage-item-fieldset');
$this->setHydrator(new DoctrineHydrator($objectManager, 'AdminMyPages\Entity\MyPageItem'))
->setObject(new MyPageItem());
// ...
$myMessageFieldset = new MyMessageFieldset($objectManager);
}
public function getInputFilterSpecification()
{
// ...
return array(
'myMessage' => array(
'required' => false
),
);
}
}
The fieldset for MyMessageFieldset looks like this:
namespace AdminMyPages\Form;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use AdminMyPages\Entity\MyMessage;
class MyMessageFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('mypage-message-fieldset');
$this->setHydrator(new DoctrineHydrator($objectManager, 'AdminMyPages\Entity\MyMessage'))
->setObject(new MyMessage());
// ...
'name' => 'myMessageText',
'type' => 'Zend\Form\Element\Textarea',
'attributes' => array(
//'type' => 'textarea',
'rows' => 10,
),
'options' => array(
'label' => 'text',
),
));
// ...
}
public function getInputFilterSpecification()
{
// ...
return array(
'myMessageText' => array(
'required' => false
),
);
// ...
}
}
in my controller I have:
$myPageItem = $this->getEntityManager()->find('AdminMyPages\Entity\MyPageItem', $mypageitemID);
$form = new EditMyPageItemForm($objectManager);
$form->setBindOnValidate(false);
$form->bind($myPageItem);
With this configuration I am able to "get" data from the MyMessage through getMyMessage(), so I know that the tables have been joined. I can bind the entity in a form and use the form elements from the MyPageItemFieldset. However, I am not able to use form elements from the MyMessageFieldset. I don't know if my problem is in how I've got the fieldset files written or if it is in how I am trying to call the form elements. Here are some trials I've made in the edit view:
// this gets the message text that can be displayed in the view:
$myMessageText = $myPageItem->getMyMessage()->getMyMessageText();
// this allows me to get a form element from the MyPageItemFieldset:
$pifs=$form->get('mypage-item-fieldset');
$myPageItemOwner = $pifs->get('myPageItemOwner');
// these are some trails for getting a form element from the MyMessageFieldset:
$mfs_1 = $pifs;
$mfs_2 = $pifs->get('myMessageFieldset');
$mfs_3 = $pifs->get('');
$mfs_4a = $pifs->get('myMessageFieldset')->getFieldsets();
$mfs_4b = $mfs_4a[0];
$mfs_5 = $pifs->$myMessageFieldset->get('mypage-message-fieldset');
$myMessageText = $mfs_1->get('myMessamypage-message-fieldsetgeText');
// No element by the name of [myMessageText] found in form
$myMessageText = $mfs_2->get('myMessageText');
// No element by the name of [myMessageFieldset] found in form
$myMessageText = $mfs_3->get('myMessageText');
// No element by the name of [mypage-message-fieldset] found in form
$myMessageText = $mfs_4b->get('myMessageText');
// No element by the name of [myMessageFieldset] found in form
$myMessageText = $mfs_5->get('myMessageText');
// Notice: Undefined variable: myMessageFieldset in ... \edit.phtml ...
Have you taken a look at the DoctrineModule Hydrator documentation? It's a bit misplaced IMO (related to DoctrineORMModule but stored in DoctrineModule) so I wouldn't be surprised if you hadn't. That section contains a full example of building complete Form infrastructure for an entity with a ManyToOne association.

Symfony2 - Set a selected value for the entity field

I'm trying to set a selected value inside an entity field. In accordance with many discussions I've seen about this topic, I tried to set the data option but this doesn't select any of the values by default:
class EventType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('place', 'entity', array(
'class' => 'RoyalMovePhotoBundle:Place',
'property' => 'name',
'empty_value' => "Choisissez un club",
'mapped' => false,
'property_path' => false,
'data' => 2
))
->add('begin')
->add('end')
->add('title')
->add('description')
;
}
// ...
}
By looking for more I've found that some people had to deactivate the form mapping to the entity. That seems logical so I tried to add 'mapped' => false to the options, without success...
If it can help, here's my controller:
class EventController extends Controller
{
// ...
public function addAction()
{
$request = $this->getRequest();
$em = $this->getDoctrine()->getManager();
$event = new Event();
$form = $this->createForm(new EventType(), $event);
$formHandler = new EventHandler($form, $request, $em);
if($formHandler->process()) {
$this->get('session')->getFlashBag()->add('success', "L'évènement a bien été ajouté.");
return $this->redirect($this->generateUrl('photo_event_list'));
}
return $this->render('RoyalMovePhotoBundle:Event:add.html.twig', array(
'form' => $form->createView()
));
}
}
And the EventHandler class:
class EventHandler extends AbstractHandler
{
public function process()
{
$form = $this->form;
$request = $this->request;
if($request->isMethod('POST')) {
$form->bind($request);
if($form->isValid()) {
$this->onSuccess($form->getData());
return true;
}
}
return false;
}
public function onSuccess($entity)
{
$em = $this->em;
$em->persist($entity);
$em->flush();
}
}
I'm a bit stuck right now, is there anyone who got an idea?
You only need set the data of your field:
class EventController extends Controller
{
// ...
public function addAction()
{
$request = $this->getRequest();
$em = $this->getDoctrine()->getManager();
$event = new Event();
$form = $this->createForm(new EventType(), $event);
// -------------------------------------------
// Suppose you have a place entity..
$form->get('place')->setData($place);
// That's all..
// -------------------------------------------
$formHandler = new EventHandler($form, $request, $em);
if($formHandler->process()) {
$this->get('session')->getFlashBag()->add('success', "L'évènement a bien été ajouté.");
return $this->redirect($this->generateUrl('photo_event_list'));
}
return $this->render('RoyalMovePhotoBundle:Event:add.html.twig', array(
'form' => $form->createView()
));
}
}
In order to option appear selected in the form, you should set corresponding value to entity itself.
$place = $repository->find(2);
$entity->setPlace($place);
$form = $this->createForm(new SomeFormType(), $entity);
....
For non-mapped entity choice fields, the method I found easiest was using the choice_attr option with a callable. This will iterate over the collection of choices and allow you to add custom attributes based on your conditions and works with expanded, multiple, and custom attribute options.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('place', 'entity', array(
//...
'choice_attr' => function($place) {
$attr = [];
if ($place->getId() === 2) {
$attr['selected'] = 'selected';
//for expanded use $attr['checked'] = 'checked';
}
return $attr;
}
))
//...
;
}
When you use the query_builder option, and the data option expects an collection instance, and you don't want to touch your controller by adding setDatas for only certain fields, and you already have your querybuilder and the ids of the repopulating options in your form type class, you can repopulate a selection as following:
// Querybuilder instance with filtered selectable options
$entities = $qb_all;
// Querybuilder instance filtered by repopulating options (those that must be marked as selected)
$entities_selected = $qb_filtered;
Then in your add() Method
'data' => $entities_selected->getQuery()->getResult(), // Repopulation
'query_builder' => $entities,
EDIT: Real use case example
You want to repopulate a checkbox group rendered with following elements:
Label: What is your favourite meal?
4 Checkboxes: Pasta, Pizza, Spaghetti, Steak
And you want to repopulate 2 Checkboxes:
Pizza, Steak
$qb_all would be a QueryBuilder instance with the all 4 selectable Checkboxes
$qb_filtered would be a new additional QueryBuilder instance with the repopulating Checkboxes Pizza, Steak. So a "filtered" version of the previous one.

Zend_Validate_Db_RecordExists with Doctrine 2?

I'm using Doctrine 2 in a Zend Framework application and require functionality similar to Zend_Validate_Db_RecordExists and Zend_Validate_Db_NoRecordExists.
For example, when a user enters a new item, I need to validate that a duplicate entry doesn't already exist. This is easy to accomplish with Zend_Db by adding the Db_NoRecordExists validator on my forms.
I tried implementing the custom-validator solution proposed here, but I can't figure out how they are communicating with Doctrine to retrieve entities (I suspect this approach may no longer work post-Doctrine 1.x).
The FAQ section of the Doctrine manual suggests calling contains() from the client code, but this only covers collections, and if possible I'd like to handle all of my form validation consistently from within my form models.
Can anyone suggest a way to use these Zend validators with Doctrine 2 DBAL configured as the database connection/resource?
It's quite straightforward, really.
I have a few Zend_Validate-type validators that talk to Doctrine ORM, so I have an abstract class that they descend from.
Here's the abstract class:
<?php
namespace TimDev\Validate\Doctrine;
abstract class AbstractValidator extends \Zend_Validate_Abstract{
/**
* #var Doctrine\ORM\EntityManager
*/
private $_em;
public function __construct(\Doctrine\ORM\EntityManager $em){
$this->_em = $em;
}
public function em(){
return $this->_em;
}
}
Here's my NoEntityExists validator:
<?php
namespace TimDev\Validate\Doctrine;
class NoEntityExists extends AbstractValidator{
private $_ec = null;
private $_property = null;
private $_exclude = null;
const ERROR_ENTITY_EXISTS = 1;
protected $_messageTemplates = array(
self::ERROR_ENTITY_EXISTS => 'Another record already contains %value%'
);
public function __construct($opts){
$this->_ec = $opts['class'];
$this->_property = $opts['property'];
$this->_exclude = $opts['exclude'];
parent::__construct($opts['entityManager']);
}
public function getQuery(){
$qb = $this->em()->createQueryBuilder();
$qb->select('o')
->from($this->_ec,'o')
->where('o.' . $this->_property .'=:value');
if ($this->_exclude !== null){
if (is_array($this->_exclude)){
foreach($this->_exclude as $k=>$ex){
$qb->andWhere('o.' . $ex['property'] .' != :value'.$k);
$qb->setParameter('value'.$k,$ex['value'] ? $ex['value'] : '');
}
}
}
$query = $qb->getQuery();
return $query;
}
public function isValid($value){
$valid = true;
$this->_setValue($value);
$query = $this->getQuery();
$query->setParameter("value", $value);
$result = $query->execute();
if (count($result)){
$valid = false;
$this->_error(self::ERROR_ENTITY_EXISTS);
}
return $valid;
}
}
Used in the context of a Zend_Form (which has an em() method like the abstract class above):
/**
* Overrides superclass method to add just-in-time validation for NoEntityExists-type validators that
* rely on knowing the id of the entity in question.
* #param type $data
* #return type
*/
public function isValid($data) {
$unameUnique = new NoEntityExists(
array('entityManager' => $this->em(),
'class' => 'PMS\Entity\User',
'property' => 'username',
'exclude' => array(
array('property' => 'id', 'value' => $this->getValue('id'))
)
)
);
$unameUnique->setMessage('Another user already has username "%value%"', NoEntityExists::ERROR_ENTITY_EXISTS);
$this->getElement('username')->addValidator($unameUnique);
return parent::isValid($data);
}
Check out the RecordExists.php and NoRecordExists.php classes in my project:-
https://github.com/andyfenna/AJF-IT/tree/master/library/AJFIT/Validate
I hope these are some use to you.
Thanks
Andrew