Related
I am currently working on a symfony 6 project where I came across the following problem:
I have to entites "Article" and "ColorPalette". The relationship between the both of these is a ManyToMany Relationship.
Now I have a form for creating new Articles where I have to define between 1 and n colors for the article. The select field uses select2 which works perfectly fine for all relationships beside the many to many one. So when I want to submit the form I get the following error:
Entity of type "Doctrine\Common\Collections\ArrayCollection" passed to
the choice field must be managed. Maybe you forget to persist it in
the entity manager?
I was able to find out that this has something to do with the field for the colorPalette which is a ManyToMany Relation but I could not figure out how to solve the issue.
My Current Code:
Article Entity Code:
/**
* #ORM\Entity(repositoryClass=ArticleRepository::class)
*/
class Article
{
...other properties
/**
* #ORM\ManyToMany(targetEntity=ColorPalette::class, inversedBy="articles")
*/
private $colorPalette;
...other functions
/**
* #return Collection|ColorPalette[]
*/
public function getColorPalette(): Collection
{
return $this->colorPalette;
}
public function addColorPalette(ColorPalette $colorPalette): self
{
if (!$this->colorPalette->contains($colorPalette)) {
$this->colorPalette[] = $colorPalette;
}
return $this;
}
public function removeColorPalette(ColorPalette $colorPalette): self
{
$this->colorPalette->removeElement($colorPalette);
return $this;
}
}
ArticleType Code:
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('title',null, array(
'label' => "title"
))
->add('titleEnglish',null, array(
'label' => "english title"
))
->add('description',null, array(
'label' => "description"
))
->add('stock',null, array(
'label' => "stock"
))
->add('status',ChoiceType::class, [
'label' => "status",
'choices' => [
'Gesperrt' => 'Gesperrt',
'Verfuegbar' => 'Verfuegbar',
'Auslaufartikel' => 'Auslaufartikel',
'Vergriffen' => 'Vergriffen'
],
'attr' => [
'class' => 'dropdown'
]
])
->add('colorPalette', EntityType::class, [
'class' => ColorPalette::class,
'multiple' => true,
'choice_label' => 'title',
'choices' => [],
'attr' => [
'class' => 'dropdown'
],
'label' => 'colors',
])
;
// Add EventSubscribers for specific fields (here: colorPalette)
$builder->addEventSubscriber(new EntityFieldListener($this->colorPaletteRepository,$this->colorPaletteClass,"colorPalette","colorPalette","id","title","colors"));
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Article::class,
]);
}
EntityFieldListener Code:
class EntityFieldListener implements EventSubscriberInterface
{
public function __construct($repository="",$class="",$fieldName="",$table="",$identifier="",$choiceLabel="",$label="") {
$this->repository = $repository;
$this->class = $class;
$this->fieldName = $fieldName;
$this->table = $table;
$this->identifier = $identifier;
$this->choiceLabel = $choiceLabel;
$this->label = $label;
}
public static function getSubscribedEvents(): array {
return [
FormEvents::PRE_SET_DATA => 'onPreSetData',
FormEvents::PRE_SUBMIT => 'onPreSubmit',
];
}
//This Event is used to prepopulate the previous select options for all Select Fields in the corresponding form
public function onPreSetData(FormEvent $event, $test): void
{
// Get the parent form
$form = $event->getForm();
// Get the data for the choice field
$data = $event->getData();
if($data->getId() != null) {
// Get the Id of the currently selected Base Article for the query builder
$functionName = 'get'.ucfirst($this->fieldName);
$selected = $data->$functionName()->getId();
$form->add($this->fieldName, EntityType::class, array(
'class' => $this->class,
'choice_label' => $this->choiceLabel,
'label' => $this->label,
'attr' => [
'class' => 'dropdown'
],
'query_builder' => function () use ($selected){
return $this->repository->createQueryBuilder($this->table)
->where($this->table.'.'.$this->identifier.' = :'.$this->identifier)
->setParameter($this->identifier, $selected);
},
));
}
}
public function onPreSubmit(FormEvent $event) {
// Get the parent form
$form = $event->getForm();
// Get the data for the choice field
$data = $event->getData();
if(isset($data[$this->fieldName]) and $data[$this->fieldName]!=null){
$selected = $data[$this->fieldName];
$form->add($this->fieldName, EntityType::class, array(
'class' => $this->class,
'choice_label' => $this->choiceLabel,
'label' => $this->label,
'attr' => [
'class' => 'dropdown'
],
'query_builder' => function () use ($selected){
//If a parameter is an array then this should be used:
// if(is_array($selected)) {
// $query = $this->repository->createQueryBuilder($this->table);
// $searchQuery="";
// for($i = 0; $i < count($selected); $i++) {
// if($i < count($selected)-1) {
// $searchQuery .= $this->table.'.'.$this->identifier.' = '.$selected[$i].' OR ';
// }
// else {
// $searchQuery .= $this->table.'.'.$this->identifier.' = '.$selected[$i];
// }
// }
// $query->andWhere($searchQuery);
// return $query;
// }
return $this->repository->createQueryBuilder($this->table)
// ->where($this->table.'.id = :id')
->where($this->table.'.'.$this->identifier.' = :'.$this->identifier)
->setParameter($this->identifier, $selected);
},
));
}
}
}
Controller Code (Only the route for inserting new entries):
#[Route('/new', name: 'new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$article = new Article();
$form = $this->createForm(ArticleType::class, $article);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//insert the new article
$this->entityManager->persist($article);
$this->entityManager->flush();
return $this->redirectToRoute($this->routeName.'_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm($this->routeName.'/new.html.twig', [
$this->routeName => $article,
'form' => $form,
]);
}
JS-Code:
//Imports
import {createSelectPicker} from './components/Select2/SelectPicker';
//Document Ready Function
$(function() {
document.getElementById("page-content").style.visibility = "visible";
createSelectPicker({id:'#article_colorPalette',minimumInputLength:1,multiple:true,selectField:'colorPalette',url:url_from_twig_ajax});
} );
Do you have an Idea how to solve this?
I would appreciate any help. :)
I'm getting error
Call to a member function buildCTCCompensationData() on null
in PayrollspendController.php on this line of code:
$compData = $this->payrollspendManager->hello($postData);
I have checked the module.config.php and __construct() method but not able to find the error. What is the issue in the code?
Please help me to resolve me the error
I have called the method properly
if any code is required will help
if want view file that will also give
Those who know zendframework help me to resolve issue
This is module.config.php
'dashboard_activity_payrollspend' => [
'type' => Literal::class,
'options' => [
'route' => '/dashboard/employer-details/activity-manage',
'constraints' => [
'action' =>'[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[a-zA-Z0-9_-]+',
],
'defaults' => [
'controller' => Controller\PayrollspendController::class,
'action' => 'add',
],
],
],
'controllers' => [
'factories' => [
Controller\PayrollspendController::class => Controller\Factory\PayrollspendControllerFactory::class
],
],
'service_manager' => [
'factories' => [
Service\PayrollspendManager::class => Service\Factory\PayrollspendManagerFactory::class
],
],
This is my controller PayrollspendController.php
<?php
namespace Dashboard\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Application\Entity\PyPayGroup;
use Application\Entity\PyPayPeriod;
//use Payroll\Form\SalaryVariationForm;
use Zend\Session\SessionManager;
use Application\Entity\CommonCompanyHeader;
use Dashboard\Form\PayrollspendForm;
class PayrollspendController extends AbstractActionController
{
private $entityManager;
private $sessionContainer;
private $pyPayPeriodClass;
private $pyPayGroupClass;
private $companyClass;
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
$this->pyPayGroupClass = $this->entityManager->getRepository(PyPayGroup::class);
$this->pyPayPeriodClass = $this->entityManager->getRepository(PyPayPeriod::class);
$this->companyClass = $this->entityManager->getRepository(CommonCompanyHeader::class);
$this->commonTranslationManager = $commonTranslationManager;
$sessionManager = new SessionManager();
$this->sessionContainer = new Container('ContainerNamespace', $sessionManager);
$arrLabelId = [];
}
public function addAction()
{
if ($this->sessionContainer->empId == "") {
return $this->redirect()->toRoute('admin_user_login');
}
if (!in_array('PY', $this->sessionContainer->arrRole)) {
if (!in_array('py_admin', $this->sessionContainer->arrRole)) {
return $this->redirect()->toRoute('dashboard_ess_index');
}
}
$reportForm = new PayrollspendForm();
$payGroup = $this->pyPayGroupClass->findBy([
'ouCode' => $this->sessionContainer->ouCode,
'langCode' => $this->sessionContainer->langCode,
'pgActive' => 1
]);
$reportForm->buildPayGroupData($payGroup);
$company = $this->companyClass->findBy([
'ouCode' => $this->sessionContainer->ouCode,
'langCode' => $this->sessionContainer->langCode
]);
$reportForm->buildCompanyData($company);
$payPeriodData = ['' => 'Select'];
$reportForm->get('payPeriod')->setValueOptions($payPeriodData);
$postData = $this->getRequest()->getPost()->toArray();
$postData['ouCode'] = $this->sessionContainer->ouCode;
$postData['langCode'] = $this->sessionContainer->langCode;
$compData = $this->payrollspendManager->hello($postData);
$groupByData = [
'' => 'Select',
'location' => 'Location',
'department' => 'Department',
'cost-center' => 'Cost center'
];
$reportForm->get('groupby')->setValueOptions($groupByData);
return new ViewModel([
'reportData' => $compData,
'form' => $reportForm,
'ouCode' => $this->sessionContainer->ouCode,
'postData' => $postData,
'langCode' => $this->sessionContainer->langCode,
'arrLabels' => $this->arrLabels
]);
$resultData->setTerminal(true);
return $resultData;
}
}
This is PayrollspendControllerFactory.php
<?php
namespace Dashboard\Controller\Factory;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Dashboard\Service\PayrollspendManager;
//use Application\Service\CommonTranslationManager;
use Dashboard\Controller\PayrollspendController;
class PayrollspendControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container,$requestedName, array $options = null)
{
$entityManager = $container->get('doctrine.entitymanager.orm_default');
$payrollspendManager = $container->get(PayrollspendManager::class);
//$hrManager = $container->get(HrManager::class);
// $commonTranslationManager = $container->get(CommonTranslationManager::class);
return new PayrollspendController($entityManager);
}
}
This PayrollspendManager.php
<?php
namespace Dashboard\Service;
//use Application\Entity\DsAnnouncement;
//use Application\Entity\TmDomain;
// The AnnouncementManager service is responsible for adding new task.
class PayrollspendManager
{
/**
* Doctrine entity manager.
* #var Doctrine\ORM\EntityManager
*/
private $entityManager;
// Constructor is used to inject dependencies into the service.
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function hello($postData)
{
$headerData = $this->getAllCTCCompensationHeader($postData);
$compData = $this->getAllCTCCompensationData($postData);
return [
'header' => $headerData,
'detail' => $compData
];
}
public function getAllCTCCompensationHeader($postData)
{
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('DISTINCT(pc.pyComPayitem) as payHeader')
->from(PyCompensationDetails::class, 'pc')
->innerJoin(PyPayItemPaygroupMap::class, 'ppipm', 'with', 'ppipm.payitemCode = pc.pyComPayitem
AND ppipm.ouCode = pc.ouCode
AND ppipm.langCode= pc.langCode
AND ppipm.pgCode= pc.pgCode')
->where('pc.ouCode = ?1')
->andWhere('pc.langCode = ?2')
->andWhere('pc.pgCode = ?3')
->andWhere('pc.isModified = ?4')
->setParameter('1', $postData['ouCode'])
->setParameter('2', $postData['langCode'])
->setParameter('3', $postData['payGroup'])
->setParameter('4', 0)
->orderBy('ppipm.orderofProcessing', 'ASC');
$compData = $queryBuilder->getQuery()->getResult();
$headerData = [
'0' => 'Employee Id',
'1' => 'Employee Name'
];
foreach ($compData as $compHeader) {
$headerData[] = $compHeader['payHeader'];
}
$headerData[] = 'PF';
$headerData[] = 'ESIC';
$headerData[] = 'Total';
return $headerData;
}
/**
* Get compensation detail data
*
* #param type $postData
* #return type
*/
public function getAllCTCCompensationData($postData)
{
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('pc.pyComEmpid, pc.amount, pc.pyComPayitem, pi.payitemDesc, hn.empFname, hn.empMname, hn.empLname')
->from(PyCompensationDetails::class, 'pc')
->innerJoin(HrEmpid::class, 'he', 'with', 'pc.ouCode = he.ouCode
and pc.langCode = he.langCode
and pc.pyComEmpid = he.empId'
)
->innerJoin(HrEmpName::class, 'hn', 'with', 'pc.ouCode = hn.ouCode
and pc.langCode = hn.langCode
and pc.pyComEmpid = hn.empId'
)
->innerJoin(PyPayItem::class, 'pi', 'with', 'pc.ouCode = pi.ouCode
and pc.langCode = pi.langCode
and pc.pyComPayitem = pi.payitemCode'
)
//->innerJoin(SmartlistData::class,'sd','with','sd.dataCode = pi.smartlistPayitemtype'
//)
->leftJoin(PyPayItemPaygroupMap::class, 'ppipm', 'with', 'ppipm.payitemCode = pi.payitemCode '
. 'AND ppipm.ouCode = pi.ouCode '
. 'AND ppipm.langCode= pi.langCode '
. 'AND ppipm.pgCode= pc.pgCode')
->where('pc.ouCode = ?1')
->andWhere('pc.langCode = ?2')
->andWhere('pc.pgCode = ?3')
->andWhere('pc.isModified = ?4')
->andWhere('he.smartlistEmpstatus != ?5')
->andWhere('pi.smartlistPayitemtype IN (94,99,100)')
->orderBy('ppipm.orderofProcessing', 'ASC')
->setParameter('1', $postData['ouCode'])
->setParameter('2', $postData['langCode'])
->setParameter('3', $postData['payGroup'])
->setParameter('4', 0)
->setParameter('5', 56);
// ->orderBy('pc.pyComEmpid');
// echo $queryBuilder->getQuery()->getSQL();
//exit;
$compData = $queryBuilder->getQuery()->getResult();
// echo '<pre>';
//print_r($compData);
// exit;
$data = [];
if (!empty($compData)) {
$total = 0;
foreach ($compData as $dataC) {
$data[$dataC['pyComEmpid']]['Employee Id'] = $dataC['pyComEmpid'];
$data[$dataC['pyComEmpid']]['Employee Name'] = sprintf('%s %s %s', $dataC['empFname'], $dataC['empMname'], $dataC['empLname']);
$data[$dataC['pyComEmpid']][$dataC['pyComPayitem']] = $dataC['amount'];
$statData = $this->getStatuoryData($postData, $dataC['pyComEmpid']);
//echo '<pre>';
// print_r($statData);
//exit;
if(isset($statData['pf']) && ($statData['pf'] == 1)){
$parameterData = $this->getParamaterData($postData, 'pf', $dataC['pyComEmpid']);
$data[$dataC['pyComEmpid']]['PF'] = $this->getPFData($postData, $parameterData);
} else {
$data[$dataC['pyComEmpid']]['PF'] = 0;
}
if(isset($statData['esic']) && ($statData['esic'] == 1)){
$parameterData = $this->getParamaterData($postData, 'esic', $dataC['pyComEmpid']);
$data[$dataC['pyComEmpid']]['ESIC'] = $this->getESICData($postData, $dataC['pyComEmpid']);
} else {
$data[$dataC['pyComEmpid']]['ESIC'] = 0;
}
$data[$dataC['pyComEmpid']]['Total'] = $this->getCTCCompensationSum($postData, $dataC['pyComEmpid'], $data[$dataC['pyComEmpid']]['PF'], $data[$dataC['pyComEmpid']]['ESIC']);
}
}
//echo "<pre>";
//print_r($data);
//exit;
return $data;
}
/**
* Get compensation sum
*
* #param array $postData
* #param string $pyComEmpid
* #return type
*/
public function getCTCCompensationSum($postData, $pyComEmpid, $pf, $esic)
{
$amountTotal = 0;
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('SUM(pc.amount) as amount')
->from(PyCompensationDetails::class, 'pc')
->where('pc.ouCode = ?1')
->andWhere('pc.langCode = ?2')
->andWhere('pc.pgCode = ?3')
->andWhere('pc.pyComEmpid = ?4')
->andWhere('pc.isModified = ?5')
->setParameter('1', $postData['ouCode'])
->setParameter('2', $postData['langCode'])
->setParameter('3', $postData['payGroup'])
->setParameter('4', $pyComEmpid)
->setParameter('5', 0);
$compData = $queryBuilder->getQuery()->getOneOrNullResult();
$amount = isset($compData['amount']) ? $compData['amount'] : 0;
$amountTotal = $amount + $pf + $esic;
return $amountTotal;
}
}
This is PayrollspendManagerFactory.php
<?php
namespace Dashboard\Service\Factory;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Dashboard\Service\PayrollspendManager;
class PayrollspendManagerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$entityManager = $container->get('doctrine.entitymanager.orm_default');
// Instantiate the service and inject dependencies
return new PayrollspendManager($entityManager);
}
}
This is PayrollspendForm
<?php
namespace Dashboard\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
//use Application\Entity\TmTask;
/**
* This form is used to collect post data.
*/
class PayrollspendForm extends Form
{
public $session;
public $entityManager;
public $ouCode;
public $langCode;
public function __construct()
{
// Define form name
parent::__construct('payrollspend-form');
// Set POST method for this form
$this->setAttribute('method', 'post');
$this->setAttribute('class', 'form-horizontal');
$this->setAttribute('id', 'payrollspend-form');
//$this->edit = $edit;
// $this->ouCode = $session->ouCode;
// $this->langCode = $session->langCode;
// $this->entityManager = $entityManager;
$this->addElements();
$this->addInputFilter();
}
protected function addElements()
{
$this->add([
'type' => 'select',
'name' => 'payPeriod',
'attributes' => [
'id' => 'payPeriod',
'class'=>'form-control'
]
]);
$this->add([
'type' => 'text',
'name' => 'payCalender',
'attributes' => [
'id' => 'payCalender',
'class'=>'form-control',
'disabled' => 'disabled'
]
]);
$this->add([
'type' => 'select',
'name' => 'companyCode',
'attributes' => [
'id' => 'companyCode',
'class'=>'form-control'
]
]);
$this->add([
'type' => 'select',
'name' => 'payGroup',
'attributes' => [
'id' => 'payGroup',
'class'=>'form-control'
]
]);
$this->add([
'type' => 'text',
'name' => 'startDate',
'attributes' => [
'id' => 'startDate',
'class' => 'form-control dpd1',
'data-date-format' => "dd-mm-yyyy"
]
]);
$this->add([
'type' => 'text',
'name' => 'endDate',
'attributes' => [
'id' => 'endDate',
'class' => 'form-control dpd1',
'data-date-format' => "dd-mm-yyyy"
]
]);
$this->add([
'type' => 'select',
'name' => 'groupby',
'attributes' => [
'id' => 'groupby',
'class'=>'form-control',
'placeholder'=>''
],
]);
$this->add([
'type' => 'submit',
'name' => 'submit',
'attributes' => [
'value' => 'Submit',
'id' => 'submitbutton',
'class' => 'btn btn-primary'
],
]);
}
private function addInputFilter()
{
$inputFilter = new InputFilter();
$this->setInputFilter($inputFilter);
}
public function buildPayGroupData($payGroup)
{
$payGroupData = [];
foreach($payGroup as $data){
$payGroupData[$data->pgCode] = $data->pgSdesc;
}
$this->get('payGroup')->setEmptyOption('select')->setValueOptions($payGroupData);
}
public function buildCompanyData($companys)
{
$companyData = ['' => 'Select'];
foreach($companys as $data){
$companyData[$data->companyCode] = $data->companyName;
}
$this->get('companyCode')->setValueOptions($companyData);
}
public function defaultDate()
{
$this->get('startDate')->setValue(date('d-m-Y'));
}
}
Assuming the call in PayrollspendController::addAction() is the problem.
$compData = $this->payrollspendManager->hello($postData);
This is because the $this->payrollspendManager variable has not been defined.
You can see in the PayrollspendControllerFactory::__invoke you have requested the service from the dependency injection container; but do not inject it into the constructor of the PayrollspendController.
// PayrollspendControllerFactory::__invoke()
$entityManager = $container->get('doctrine.entitymanager.orm_default');
$payrollspendManager = $container->get(PayrollspendManager::class);
return new PayrollspendController($entityManager);
You should update the factory :
return new PayrollspendController($entityManager, $payrollspendManager);
And also the constructor of the controller to allow the new argument (while you are there you can also type hint on the expected interface)
use \Doctrine\ORM\EntityManager;
use \Dashboard\Service\PayrollspendManager;
class PayrollspendController extends AbstractActionController
{
// ...
private $entityManager;
private $payrollspendManager;
public function __construct(
EntityManager $entityManager,
PayrollspendManager $payrollspendManager
){
$this->entityManager = $entityManager;
$this->payrollspendManager = $payrollspendManager;
}
// ...
}
One model belongs to other. I need to apply "after find" filter in child model, so I try to do:
class Parent extends \lithium\data\Model
{
public $hasMany = array(
'Childs' => array(
'to' => 'app\models\Child',
'key' => array('parent_id' => 'parent_id'),
),
);
}
// ...
class Child extends \lithium\data\Model
{
protected $_meta = array(
'source' => 'child',
'key' => 'child_id',
);
public $belongsTo = array(
'Parent' => array(
'to' => 'app\models\Parent',
'key' => 'parent_id',
)
);
}
Child::applyFilter('find', function($self, $params, $chain)
{
$entity = $chain->next($self, $params, $chain);
if ( is_object($entity) )
{
$entity->notes = empty($entity->notes) ? array() : unserialize($entity->notes);
}
return $entity;
});
Then I try to find all parents with Parent::all(array('with' => 'Child', 'conditions' => $conditions)); and filter doesn`t apply :(
What can be done?
I think what you are looking for is a filter on the Parent find method:
Parent::applyFilter('find', function($self, $params, $chain)
{
$result = $chain->next($self, $params, $chain);
if (isset($params['options']['with']) && $params['options']['with'] === 'Child') {
$result = $result->map(function($parent) {
if ($parent->child) {
$child = &$parent->child;
$child->notes = empty($child->notes) ? array() : unserialize($child->notes);
}
return $parent;
});
}
return $result;
});
I'm not sure why you expect this to work. Filters act on the class methods you apply them to.
EDIT : My main question has now become 'How do I get the ServiceManager with the doctrine entity manager into the hands of my form, element, and input classes in some clean way?' Read on to see the full post.
I'm going to try and ask by example here so bear with me. Let me know where I'm going wrong/right or where I could improve
I'm trying to create a registration form. I could use ZfcUser module but I want to do this on my own. I'm using ZF2 with Doctrine2 as well so that leads me away from that module a bit.
My strategy was this,
Create a form class called registration form
Create separate 'element' classes for each element where each element will have an input specification
Since each element is a separate class from the form I can unit test each one separately.
All seemed fine until I wanted to add a validator to my username element that would check that the username is NOT is use yet.
Here is the code thus far
namepsace My\Form;
use Zend\Form\Form,
Zend\Form\Element,
Zend\InputFilter\Input,
Zend\InputFilter\InputFilter,
/**
* Class name : Registration
*/
class Registration
extends Form
{
const USERNAME = 'username';
const EMAIL = 'email';
const PASSWORD = 'password';
const PASS_CONFIRM = 'passwordConfirm';
const GENDER = 'gender';
const CAPTCHA = 'captcha';
const CSRF = 'csrf';
const SUBMIT = 'submit';
private $captcha = 'dumb';
public function prepareForm()
{
$this->setName( 'registration' );
$this->setAttributes( array(
'method' => 'post'
) );
$this->add( array(
'name' => self::USERNAME,
'type' => '\My\Form\Element\UsernameElement',
'attributes' => array(
'label' => 'Username',
'autofocus' => 'autofocus'
)
)
);
$this->add( array(
'name' => self::SUBMIT,
'type' => '\Zend\Form\Element\Submit',
'attributes' => array(
'value' => 'Submit'
)
) );
}
}
I removed a lot that I think isn't necessary. Here is my username element below.
namespace My\Form\Registration;
use My\Validator\UsernameNotInUse;
use Zend\Form\Element\Text,
Zend\InputFilter\InputProviderInterface,
Zend\Validator\StringLength,
Zend\Validator\NotEmpty,
Zend\I18n\Validator\Alnum;
/**
*
*/
class UsernameElement
extends Text
implements InputProviderInterface
{
private $minLength = 3;
private $maxLength = 128;
public function getInputSpecification()
{
return array(
'name' => $this->getName(),
'required' => true,
'filters' => array(
array( 'name' => 'StringTrim' )
),
'validators' =>
array(
new NotEmpty(
array( 'mesages' =>
array(
NotEmpty::IS_EMPTY => 'The username you provided is blank.'
)
)
),
new AlNum( array(
'messages' => array( Alnum::STRING_EMPTY => 'The username can only contain letters and numbers.' )
)
),
new StringLength(
array(
'min' => $this->getMinLength(),
'max' => $this->getMaxLength(),
'messages' =>
array(
StringLength::TOO_LONG => 'The username is too long. It cannot be longer than ' . $this->getMaxLength() . ' characters.',
StringLength::TOO_SHORT => 'The username is too short. It cannot be shorter than ' . $this->getMinLength() . ' characters.',
StringLength::INVALID => 'The username is not valid.. It has to be between ' . $this->getMinLength() . ' and ' . $this->getMaxLength() . ' characters long.',
)
)
),
array(
'name' => '\My\Validator\UsernameNotInUse',
'options' => array(
'messages' => array(
UsernameNotInUse::ERROR_USERNAME_IN_USE => 'The usarname %value% is already being used by another user.'
)
)
)
)
);
}
}
Now here is my validator
namespace My\Validator;
use My\Entity\Helper\User as UserHelper,
My\EntityRepository\User as UserRepository;
use Zend\Validator\AbstractValidator,
Zend\ServiceManager\ServiceManagerAwareInterface,
Zend\ServiceManager\ServiceLocatorAwareInterface,
Zend\ServiceManager\ServiceManager;
/**
*
*/
class UsernameNotInUse
extends AbstractValidator
implements ServiceManagerAwareInterface
{
const ERROR_USERNAME_IN_USE = 'usernameUsed';
private $serviceManager;
/**
*
* #var UserHelper
*/
private $userHelper;
protected $messageTemplates = array(
UsernameNotInUse::ERROR_USERNAME_IN_USE => 'The username you specified is being used already.'
);
public function isValid( $value )
{
$inUse = $this->getUserHelper()->isUsernameInUse( $value );
if( $inUse )
{
$this->error( UsernameNotInUse::ERROR_USERNAME_IN_USE, $value );
}
return !$inUse;
}
public function setUserHelper( UserHelper $mapper )
{
$this->userHelper = $mapper;
return $this;
}
/**
* #return My\EntityRepository\User
*/
public function getUserHelper()
{
if( $this->userHelper == null )
{
$this->setUserHelper( $this->getServiceManager()->get( 'doctrine.entitymanager.orm_default' )->getObjectRepository( 'My\Entity\User') );
}
return $this->userHelper;
}
public function setServiceManager( ServiceManager $serviceManager )
{
echo get_class( $serviceManager );
echo var_dump( $serviceManager );
$this->serviceManager = $serviceManager;
return $this;
}
/**
*
* #return ServiceManager
*/
public function getServiceManager( )
{
return $this->serviceManager;
}
}
Why did this seem like a good idea to me?
It seemed like a good testability/re-use choice to make since I could re-use the elements separately across my application if need be.
I could unit test each Input generated by each element to make sure it correctly accepts/rejects input.
This is the example of my unit test for the element
public function testFactoryCreation()
{
$fac = new Factory();
$element = $fac->createElement( array(
'type' => '\My\Form\Registration\UsernameElement'
) );
/* #var $element \My\Form\Registration\UsernameElement */
$this->assertInstanceOf( '\My\Form\Registration\UsernameElement',
$element );
$input = $fac->getInputFilterFactory()->createInput( $element->getInputSpecification() );
$validators = $input->getValidatorChain()->getValidators();
/* #var $validators \Zend\Validator\ValidatorChain */
$expectedValidators = array(
'Zend\Validator\StringLength',
'Zend\Validator\NotEmpty',
'Zend\I18n\Validator\Alnum',
'My\Validator\UsernameNotInUse'
);
foreach( $validators as $validator )
{
$actualClass = get_class( $validator['instance'] );
$this->assertContains( $actualClass, $expectedValidators );
switch( $actualClass )
{
case 'My\Validator\UsernameNotInUse':
$helper = $validator['instance']->getUserHelper();
//HAVING A PROBLEM HERE
$this->assertNotNull( $helper );
break;
default:
break;
}
}
}
The problem I'm having is that the validator can't fetch the UserHelper properly, which is really a UserRepository from doctrine. The reason this is happening is because the validators only get access to the ValidatorPluginManager as a ServiceManager rather than having access to the application wide ServiceManager.
I get this error for the Validator portion, although if I call the same get method on the general service manager it works with no problems.
1) Test\My\Form\Registration\UsernameElementTest::testFactoryCreation
Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.entitymanager.orm_default
The var_dump( $serviceManager ) in validator shows me it is of the class ValidatorPluginManager.
I tried putting a factory in the service_manager entry like so
'service_manager' => array(
'factories' => array(
'My\Validator\UsernameNotInUse' => function( $sm )
{
$validator = new \My\Validator\UsernameNotInUse();
$em = $serviceManager->get( 'doctrine.entitymanager.orm_default' );
/* #var $em \Doctrine\ORM\EntityManager */
$validator->setUserHelper( $em->getRepository( '\My\Entity\User' ) );
return $validator;
}
)
but that didn't work because it's not consulting the application level service manager.
So, overall, here are my questions :
Is this strategy of separating the form and elements a good one? Should I keep going this way? What are alternatives? ( I'm for breaking stuff up for the sake of testability ) I was going to test ONLY the form itself originally with a combination of ALL the inputs but it seemed like I'd be trying to do too much.
How do I resolve the issue I have above?
Should I be using the Form/Element/Input parts of Zend in some other way that I'm not seeing?
this is my validator, using a static method to inject the entityManager and working with any doctine entity.
<?php
namespace Base\Validator;
use Traversable;
use Zend\Stdlib\ArrayUtils;
use Zend\Validator\AbstractValidator;
use Doctrine\ORM\EntityManager;
class EntityUnique extends AbstractValidator
{
const EXISTS = 'exists';
protected $messageTemplates = array(
self::EXISTS => "A %entity% record already exists with %attribute% %value%",
);
protected $messageVariables = array(
'entity' => '_entity',
'attribute' => '_attribute',
);
protected $_entity;
protected $_attribute;
protected $_exclude;
protected static $_entityManager;
public static function setEntityManager(EntityManager $em) {
self::$_entityManager = $em;
}
public function getEntityManager() {
if (!self::$_entityManager) {
throw new \Exception('No entitymanager present');
}
return self::$_entityManager;
}
public function __construct($options = null)
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($token);
}
if (is_array($options)) {
if (array_key_exists('entity', $options)) {
$this->_entity = $options['entity'];
}
if (array_key_exists('attribute', $options)) {
$this->_attribute = $options['attribute'];
}
if (array_key_exists('exclude', $options)) {
if (!is_array($options['exclude']) ||
!array_key_exists('attribute', $options['exclude']) ||
!array_key_exists('value', $options['exclude'])) {
throw new \Exception('exclude option must contain attribute and value keys');
}
$this->_exclude = $options['exclude'];
}
}
parent::__construct(is_array($options) ? $options : null);
}
public function isValid($value, $context = null)
{
$this->setValue($value);
$queryBuilder = $this->getEntityManager()
->createQueryBuilder()
->from($this->_entity, 'e')
->select('COUNT(e)')
->where('e.'. $this->_attribute . ' = :value')
->setParameter('value', $this->getValue());
if ($this->_exclude) {
$queryBuilder = $queryBuilder->andWhere('e.'. $this->_exclude['attribute'] . ' != :exclude')
->setParameter('exclude', $this->_exclude['value']);
}
$query = $queryBuilder->getQuery();
if ((integer)$query->getSingleScalarResult() !== 0) {
$this->error(self::EXISTS);
return false;
}
return true;
}
}
ie. i'm using it for theese form elements which are also tested and working fine:
<?php
namespace User\Form\Element;
use Zend\Form\Element\Text;
use Zend\InputFilter\InputProviderInterface;
class Username extends Text implements InputProviderInterface
{
public function __construct() {
parent::__construct('username');
$this->setLabel('Benutzername');
$this->setAttribute('id', 'username');
}
public function getInputSpecification() {
return array(
'name' => $this->getName(),
'required' => true,
'filters' => array(
array(
'name' => 'StringTrim'
),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'break_chain_on_failure' => true,
'options' => array(
'messages' => array(
'isEmpty' => 'Bitte geben Sie einen Benutzernamen ein.',
),
),
),
),
);
}
}
When creating a new user
<?php
namespace User\Form\Element;
use Zend\InputFilter\InputProviderInterface;
use User\Form\Element\Username;
class CreateUsername extends Username implements InputProviderInterface
{
public function getInputSpecification() {
$spec = parent::getInputSpecification();
$spec['validators'][] = array(
'name' => 'Base\Validator\EntityUnique',
'options' => array(
'message' => 'Der name %value% ist bereits vergeben.',
'entity' => 'User\Entity\User',
'attribute' => 'username',
),
);
return $spec;
}
}
when editin an existing user
<?php
namespace User\Form\Element;
use Zend\InputFilter\InputProviderInterface;
use User\Form\Element\Username;
class EditUsername extends Username implements InputProviderInterface
{
protected $_userId;
public function __construct($userId) {
parent::__construct();
$this->_userId = (integer)$userId;
}
public function getInputSpecification() {
$spec = parent::getInputSpecification();
$spec['validators'][] = array(
'name' => 'Base\Validator\EntityUnique',
'options' => array(
'message' => 'Der name %value% ist bereits vergeben.',
'entity' => 'User\Entity\User',
'attribute' => 'username',
'exclude' => array(
'attribute' => 'id',
'value' => $this->_userId,
),
),
);
return $spec;
}
}
Hey there, I'm trying to validate a form with Zend_Validate and Zend_Form.
My element:
$this->addElement('text', 'username', array(
'validators' => array(
array(
'validator' => 'Db_NoRecordExists',
'options' => array('user','username')
)
)
));
For I use Doctrine to handle my database, Zend_Validate misses a DbAdapter. I could pass an adapter in the options, but how do I combine Zend_Db_Adapter_Abstract and Doctrine?
Is there maybe an easyer way to get this done?
Thanks!
Solved it with an own Validator:
<?php
class Validator_NoRecordExists extends Zend_Validate_Abstract
{
private $_table;
private $_field;
const OK = '';
protected $_messageTemplates = array(
self::OK => "'%value%' ist bereits in der Datenbank"
);
public function __construct($table, $field) {
if(is_null(Doctrine::getTable($table)))
return null;
if(!Doctrine::getTable($table)->hasColumn($field))
return null;
$this->_table = Doctrine::getTable($table);
$this->_field = $field;
}
public function isValid($value)
{
$this->_setValue($value);
$funcName = 'findBy' . $this->_field;
if(count($this->_table->$funcName($value))>0) {
$this->_error();
return false;
}
return true;
}
}
Used like that:
$this->addElement('text', 'username', array(
'validators' => array(
array(
'validator' => new Validator_NoRecordExists('User','username')
)
)
));