For the category structure on my proejct I'm building an entity. For the add form I use the DoctrineObject hydrator. When there is a value for the $parent this works fine, but whe there is no parent it gives me an error because there is no id to select the parent with. The value of the parent property should be null in this case.
I'd create an filter to do so. This filter is executed but the hydrator doesn't seem to get what I want it to do.
Does anybody know how to solve this?
My entity:
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Flex\Entity\Entity;
/**
* #Gedmo\Tree(type="materializedPath")
* #ORM\Table(name="categories")
* #ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\MaterializedPathRepository")
*/
class Category extends Entity
{
/**
* #ORM\OneToMany(mappedBy="parent", targetEntity="FlexCategories\Entity\Category")
*/
protected $children;
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
protected $id;
/**
* #Gedmo\TreeLevel
* #ORM\Column(nullable=true, type="integer")
*/
protected $level;
/**
* #ORM\Column(length=64, type="string")
*/
protected $name;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(inversedBy="children", targetEntity="FlexCategories\Entity\Category")
* #ORM\JoinColumns({
* #ORM\JoinColumn(onDelete="SET NULL", referencedColumnName="id")
* })
*/
protected $parent;
/**
* #Gedmo\TreePath(appendId=false, endsWithSeparator=false, separator="/", startsWithSeparator=true)
* #ORM\Column(length=255, nullable=true, type="string", unique=true)
*/
protected $path;
/**
* #Gedmo\Slug(fields={"name"}, unique=false)
* #Gedmo\TreePathSource
* #ORM\Column(length=64)
*/
protected $slug;
public function setId($value)
{
$this->id = $value;
}
public function setName($value)
{
$this->name = $value;
}
public function setParent($value)
{
$this->parent = $value;
}
}
My form:
use DoctrineModule\Stdlib\Hydrator\DoctrineObject;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class CategoryForm extends Form implements InputFilterProviderInterface, ServiceManagerAwareInterface
{
private $_serviceManager;
public function init()
{
// Init hydrator
$hydrator = new DoctrineObject($this->_serviceManager->get('doctrine.entitymanager.orm_default'),
'FlexCategories\Entity\Category');
// Set form basic configurations
$this->setAttribute('method', 'post')
->setHydrator($hydrator);
// Add parent field
$this->add(array(
'name' => 'parent',
'type' => 'Zend\Form\Element\Hidden',
));
// Add name field
$this->add(array(
'attributes' => array(
'required' => 'required',
),
'name' => 'name',
'options' => array(
'label' => 'Name',
),
'type' => 'Zend\Form\Element\Text',
));
// Add description field
$this->add(array(
'name' => 'description',
'options' => array(
'label' => 'Description',
),
'type' => 'Zend\Form\Element\Textarea',
));
// Add CSRF element
$this->add(array(
'name' => 'csrf',
'type' => 'Zend\Form\Element\Csrf',
));
// Add submit button
$this->add(array(
'attributes' => array(
'type' => 'submit',
'value' => 'Save',
),
'name' => 'submit',
));
}
public function getInputFilterSpecification()
{
return array(
'description' => array(
'filters' => array(
array(
'name' => 'Zend\Filter\StringTrim'
),
),
'required' => false,
),
'name' => array(
'filters' => array(
array(
'name' => 'Zend\Filter\StringTrim'
),
),
'required' => true,
'validators' => array(
array(
'name' => 'Flex\Validator\EntityUnique',
'options' => array(
'entity' => 'FlexCategories\Entity\Category',
'filter' => array(
array('property' => 'parent',
'value' => array('_context', 'parent')),
),
'property' => 'name',
'serviceLocator' => $this->_serviceManager,
),
),
),
),
'parent' => array(
'filters' => array(
array(
'name' => 'Flex\Filter\NullIfEmpty'
),
),
'required' => false,
),
);
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->_serviceManager = $serviceManager;
$this->init();
return $this;
}
}
My controller:
use Flex\Controller\AbstractController;
use FlexCategories\Entity\Category;
use FlexCategories\Form\CategoryForm;
class AdminController extends AbstractController
{
public function addAction()
{
// Load form
$form = $this->getServiceLocator()->get('FlexCategories\Form\CategoryForm');
// Create and bind new entity
$category = new Category();
$form->bind($category);
// Load parent category if present
$parentId = $this->params()->fromRoute('id', null);
if ($parentId !== null)
{
if (!is_numeric($parentId))
throw new \InvalidArgumentException('Invalid parent id specified');
$entityManager = $this->getEntityManager();
$repository = $entityManager->getRepository('FlexCategories\Entity\Category');
$parent = $repository->find($parentId);
if (!$parent)
throw new \InvalidArgumentException('Invalid parent id specified');
$form->get('parent')->setValue($parent->getId());
}
// Process request
$request = $this->getRequest();
if ($request->isPost())
{
$form->setData($request->getPost());
if ($form->isValid())
{
$entityManager = $this->getEntityManager();
$entityManager->persist($category);
$entityManager->flush();
$this->flashMessenger()->addSuccessMessage(sprintf('The category "%1$s" has succesfully been added.', $category->getName()));
return $this->redirect()->toRoute($this->getEvent()->getRouteMatch()->getMatchedRouteName());
}
}
// Return form
return array(
'form' => $form,
);
}
public function indexAction()
{
// Load all categories
$entityManager = $this->getEntityManager();
$repository = $entityManager->getRepository('FlexCategories\Entity\Category');
$categories = $repository->findBy(array(), array('path' => 'asc'));
return array(
'categories' => $categories,
);
}
}
My database:
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) DEFAULT NULL,
`level` int(11) DEFAULT NULL,
`name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`path` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`slug` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQ_3AF34668B548B0F` (`path`),
KEY `IDX_3AF34668727ACA70` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `categories`
ADD CONSTRAINT `FK_3AF34668727ACA70` FOREIGN KEY (`parent_id`) REFERENCES `categories` (`id`) ON DELETE SET NULL;
I'd solve this problem by create an "HiddenElement" element based on "DoctrineModule\Form\ElementObjectSelect" and use this as the input type.
You need a strategy which handles '' values. ('' != null) as ocramius points out its possible to haven an primary key with ''.
you ran into this problem as soon as you use the "empty_option" currently u cant just set null to it, the form post will always transfer ''.
see https://github.com/doctrine/DoctrineModule/pull/119
see https://github.com/doctrine/DoctrineModule/pull/106
so add a strategy for this field to the hydrator to convert '' to null.
this could look like:
use Zend\Stdlib\Hydrator\Strategy\DefaultStrategy;
class ForeignKey extends DefaultStrategy
{
public function hydrate($value)
{
if($value == '') {
return NULL;
}
return $value;
}
}
Related
i'm trying to insert data to database but submitted forms does nothing.
this is my service manager:
class AutosManager
{
/**
* Entity manager.
* #var Doctrine\ORM\EntityManager;
*/
private $entityManager;
/**
* Constructor.
*/
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function addNewAutos($data)
{
$autos = new Autos();
$autos->setTitle($data['title']);
$autos->setDescription($data['description']);
$currentDate = date('Y-m-d H:i:s');
$autos->setDateCreated($currentDate);
$this->entityManager->persist($autos);
$this->entityManager->flush();
}
this is my controller addAction
public function addAction()
{
// Create the form.
$form = new PostForm();
if ($this->getRequest()->isPost()) {
// Get POST data.
$data = $this->params()->fromPost();
// Fill form with data.
$form->setData($data);
if ($form->isValid()) {
// Get validated form data.
$data = $form->getData();
$this->AutosManager->addNewAutos($data);
return $this->redirect()->toRoute('retrieve');
}
}
return new ViewModel([
'form' => $form
]);
}
i can retrieve data from database to the index page but i cannot add. hope to find the solution.
this is my Autos Entity
namespace Retrieve\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="\Retrieve\Repository\AutosRepository")
* #ORM\Table(name="auto")
*/
class Autos
{
/**
* #ORM\Id
* #ORM\Column(name="id")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(name="title")
*/
protected $title;
/**
* #ORM\Column(name="description")
*/
protected $description;
/**
* #ORM\Column(name="featured")
*/
protected $featured;
/**
* #ORM\Column(name="date_created")
*/
protected $dateCreated;
/**
* Returns ID of this post.
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Sets ID of this post.
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Returns title.
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Sets title.
* #param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Returns featured.
* #return integer
*/
public function getFeatured()
{
return $this->featured;
}
/**
* Sets featured.
* #param integer $featured
*/
public function setFeatured($featured)
{
$this->featured = $featured;
}
/**
* Returns post description.
*/
public function getDescription()
{
return $this->description;
}
/**
* Sets post description.
* #param type $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Returns the date when this post was created.
* #return string
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* Sets the date when this post was created.
* #param string $dateCreated
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
}
}
hope this helps to find solution.
I found the problem: it was an inputfilter element I wasn't using that was authenticating in forms. But the solution only brings me to a different problem:
Notice: Undefined index: title in C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php on line 38
Notice: Undefined index: description in C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php on line 39
Notice: Undefined index: featured in C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php on line 58
Message:
An exception occurred while executing 'INSERT INTO auto (title, description, featured, date_created) VALUES (?, ?, ?, ?)' with params [null, null, null, "2017-06-15 05:04:44"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null
this is my form and fieldset
use Zend\Form\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use BusinessGhana\Entity\Autos;
class AddFieldset extends Fieldset
{
protected $objectManager;
public function init()
{
$this->add([
'type' => 'text',
'name' => 'title',
'attributes' => [
'id' => 'autoTitle'
],
'options' => [
'label' => 'Title',
'display_empty_item' => true,
'empty_item_label' => 'Maximum of 60 characters',
],
]);
$this->add([
'type' => 'textarea',
'name' => 'description',
'attributes' => [
'id' => 'autoDescription'
],
'options' => [
'label' => 'Description',
'display_empty_item' => true,
'empty_item_label' => 'description',
],
]);
$this->add([
'type' => 'radio',
'name' => 'featured',
'attributes' => [
'id' => 'autoFeatured'
],
'options' => array(
'label' => 'Featured',
'value_options' => array(
array('value' => '0',
'label' => 'No',
'selected' => true,
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-default',
),
),
array(
'value' => '1',
'label' => 'Yes',
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-danger',
),
),
),
'column-size' => 'sm-12',
'label_attributes' => array(
'class' => 'col-sm-2',
),
),
]);
}
}
use Zend\Form\Form;
//use Zend\InputFilter\InputFilter;
class AddForm extends Form
{
public function init()
{
$this->add([
'name' => 'dependentForm',
'type' => AddFieldset::class,
]);
$this->add([
'type' => 'submit',
'name' => 'submit',
'attributes' => [
'value' => 'Submit',
],
]);
}
}
i know hydration can solve this problem but i dont know how to use it yet.
I am pretty new to Zend Framework 2 and Doctrine 2, so I am not even sure how to search or debug my problem.
I have 3 database tables
1. advert
id
adverttitle
...
2. category
id
categoryname
...
3. advert_category
advert_id
category_id
I have created 2 Entities, Advert and Category. I have now got a Form where I show the Categories to choose from. I use jQuery to display the categories as a list instead of a dropdown, together with a selectable function. So when you click on a category, the value of this listelement gets entered into a hidden input field called categories.
Everything works fine, besides that when I display the form, the hidden categories input field got a value of Doctrine\Common\Collections\ArrayCollection#000000000..... instead of being empty. What am I doing wrong here? I have tried to find a solution, but unsuccessfully.
I have chosen a ManyToMany Relationship because I want to be able to save more then 1 category in the end. Currently it is only working with 1, but this way I should be able to change this at a later time.
Here my Advert entity:
namespace Advert\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use DateTime;
/** Advert
*
* #ORM\Table(name="advert")
* #ORM\Entity(repositoryClass="Advert\Repository\AdvertRepository")
*/
class Advert
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="advert_title", type="string", length=255, nullable=true)
*/
private $advertTitle;
/**
* #ORM\ManyToMany(targetEntity="Category", inversedBy="adverts", cascade={"persist"})
* #ORM\JoinTable(name="advert2category")
*/
private $categories;
public function __construct()
{
$this->categories = new ArrayCollection();
}
/**
* Set categories
*
* #param ArrayCollection $category
* #return Advert
*/
public function setCategories($categories)
{
$this->categories = $categories;
return $this;
}
/**
* Get categories
*
* #return ArrayCollection
*/
public function getCategories()
{
return $this->categories;
}
/**
* #param Collection $categories
*/
public function addCategories($categories)
{
foreach ($categories as $category) {
$this->categories->add($category);
}
}
/**
* #param Collection $categories
*/
public function removeCategories($categories)
{
foreach($categories as $category){
$this->categories->removeElement($category);
}
}
Is there an Error in the Advert Entity which causes this? I hope someone can help. I have this problems since weeks and can not get it to work correctly.
UPDATE -- added my Form and part in controller to call form
The below Form displays 2 Dropdown Elements and 2 Hidden Input Fields. The 2 Dropdown Fields get turned into a selectable List via jQuery. When you click on a List Element from the Maincategory, the Subcategories show up for that chosen Maincategory again as a selectable list. The MaincategoryID gets then entered into the hidden categoryID Field. As soon you choose the Subcategory from the List, the id of that category gets written in the hidden categories field. A click on the "next" button saves the value of $_POST['categories'] together with the advertID in my linking table.
use Zend\Form\Form;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Doctrine\Common\Persistence\ObjectManager;
class CategoryForm extends Form implements ObjectManagerAwareInterface
{
protected $objectManager;
public function __construct()
{
$this->setInputFilter(new AdvertFilter());
parent::__construct('category');
}
public function init()
{
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'categories',
'attributes' => array(
'type' => 'hidden',
'id' => 'categories',
),
'options'=> array(
'label'=> 'categories',
),
));
$this->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'categoriesList',
'options' => array(
'object_manager' => $this->getObjectManager(),
'label' => 'Main Category',
'target_class' => 'Advert\Entity\Category',
'property' => 'name',
'is_method' => true,
'find_method' => array(
'name' => 'getMainCategories',
),
),
'allow_empty' => true,
'required' => false,
'attributes' => array(
'id' => 'categoryList',
'multiple' => true,
)
)
);
$this->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'subcategoryList',
'options' => array(
'object_manager' => $this->getObjectManager(),
'label' => 'Sub Category',
'target_class' => 'Advert\Entity\Category',
'property' => 'name',
'is_method' => true,
'find_method' => array(
'name' => 'getSubCategories',
),
),
'allow_empty' => true,
'required' => false,
'attributes' => array(
'id' => 'subcategoryList',
'multiple' => true,
)
)
);
$this->add(array(
'type' => 'hidden',
'name' => 'categoryID',
'options'=> array(
'label'=> 'categoryID'),
'attributes' => array(
'id' => 'categoryID',
'value' => '1',
)
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Next',
'id' => 'submitbutton',
),
));
}
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
public function getObjectManager()
{
return $this->objectManager;
}
}
In my Controller I call my form the following way:
$sl = $this->getServiceLocator();
$form = $sl->get('FormElementManager')->get('\Advert\Form\CreateForm');
# create a new, empty entity
$advert = new Advert();
# set the hydrator to connect form and entity
$form->setHydrator(new DoctrineHydrator($this->getEntityManager(),'Advert\Entity\Advert'));
# connect form and entity
$form->bind($advert);
The first thing is, bidirectional relationships doesn't uses join tables. Your mapping seems like bi-directional however you're trying to use the third table: advert_category.
I recommend to change mapping of the $categories property of Advert entity to a uni-directional relationship:
class Advert
{
// ...
/**
* #ORM\ManyToMany(targetEntity="Category")
* #ORM\JoinTable(name="advert_category",
* joinColumns={#ORM\JoinColumn(name="advert_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="category_id", referencedColumnName="id")}
* )
**/
protected $categories;
// ...
}
Also you should implement the addCategories(Collection $categories) and removeCategories(Collection $categories) methods inside Advert entity if you want to take advantage of DoctrineObject hydrator. (I'm assuming that you're using DoctrineORMModule).
At this point, your Category entity shouldn't know anything about Advert and you CAN'T DIRECTLY ACCESS all adverts from a category instance via an entity method like $category->getAdverts(). However when needed, you can easily write a getAdvertsByCategoryId($categoryId) method in your AdvertRepository.
The last detail is, you should have a CategoryFieldset (which also needs to use Category entity as object) and you have to point this fieldset in your form's categories element using target_elementconfiguration key or directly providing instance's itself.
For example:
$formManager = $serviceLocator->get('FormElementManager');
$form = $formManager->get('your\form\name');
$form->add(
array(
'name' => 'categories',
'type' => 'Zend\Form\Element\Collection',
'options' => array(
'target_element' => $formManager->get('your\fieldset\name');
// or you can do this but probably you will also need $entityManager
// inside the CategoryFieldset
// 'target_element' => new CategoryFieldset();
),
)
);
I strongly recommend using of FormElementManager to get form and fieldset instances instaed of directly instantiate them by new AdvertForm() and new CategoryFieldset(). Also writing an AbstractFormElementFactory would be good practice to inject $entityManager like dependencies to your fieldsets and forms, the right way.
Hope it helps.
After browsing several tutorials reagrding Zend2 /Doctrine 2 and Fieldsets i finally figured out the filedset/collction.
But new "fields" wont be added to the database table. Any changes in the existing elements are stored. Major Class Organization callsthe fieldset ActBusinessCountry:
Major Class Organization
class Organization {
protected $inputFilter;
/**
* #ORM\Id
* #ORM\Column(type="integer");
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $organizational;
/**
* #ORM\Column(type="string")
*/
protected $structure;
/**
* #param \Doctrine\Common\Collections\ArrayCollection
* #ORM\OneToMany(targetEntity="People\Entity\ActBusinessCountry",mappedBy="company",cascade={"persist", "merge", "refresh", "remove"})
*/
protected $organizaton_opcountry;
public function __construct()
{
$this->organizaton_opcountry = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #param \Doctrine\Common\Collections\ArrayCollection $organizaton_opcountry
*/
public function addOrganizaton_opcountry(Collection $organizaton_opcountry)
{
foreach ($organizaton_opcountry as $opcountry) {
$this->organizaton_opcountry->add($opcountry);
}
return $this->organizaton_opcountry;
}
public function removeOrganizaton_opcountry(Collection $organizaton_opcountry)
{
foreach ($organizaton_opcountry as $opcountry) {
$tag->setCompany(null);
$this->organizaton_opcountry->removeElement($opcountry);
}
}
/**
* #return Collection
*/
public function getOrganizaton_opcountry()
{
return $this->organizaton_opcountry;
}
Sub class/fieldset is ActBusinessCountry
class ActBusinessCountry {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* #ORM\ManyToOne(targetEntity="People\Entity\Organization",inversedBy="organizaton_opcountry")
* #ORM\JoinColumn(name="company_id", referencedColumnName="id")
*/
public $company;
/**
* #ORM\Column(type="string")
*/
public $country;
/**
* #ORM\Column(type="string")
*/
public $company_id;
/**
* Allow null to remove association
*/
public function setId($id = null)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function getCompany()
{
return $this->company;
}
public function setCompany(Company $company = null)
{
$this->company = $company;
}
public function getCountry()
{
return $this->country;
}
public function setCountry($country)
{
$this->country = $country;
}
}
Organization Form:
$countrySelect = new ActBusinessCountryFieldset($objectManager);
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'organizaton_opcountry',
'options' => array(
'should_create_template' => true,
'use_as_base_fieldet' => true,
'count' => 1,
'allow_add' => true,
'target_element' => $countrySelect,
),
));
Fielset Elements:
class ActBusinessCountryFieldset extends Fieldset implements ObjectManagerAwareInterface
{
protected $objectManager;
public function __construct(ObjectManager $objectManager)
{
$this->setObjectManager($objectManager);
parent::__construct('fieldset');
$this ->setHydrator(new DoctrineHydrator($objectManager, 'People\Entity\ActBusinessCountry'))
->setObject(new \People\Entity\ActBusinessCountry());
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'country',
'attributes' => array(
'class' => 'form-control input-small',
),
'options' => array(
'object_manager' => $this->getObjectManager(),
'target_class' => 'People\Entity\Country',
'value' => 'country',
'property' => 'country_name',
'class'=>'form-control',
'label_attributes' => array(
'class'=> 'col-sm-3 control-label',
),
),
));
}
public function getInputFilterSpecification()
{
return array(
'id' => array(
'required' => false
)
);
return array(
'country' => array(
'required' => true
)
);
}
Controller Flushing Part:
if ($this->request->isPost()) {
// Cancel button
if(isset($_POST['cancel'])) {
echo "<script>window.close();</script>";
}
$form->setData($this->request->getPost());
var_dump($this->request->getPost('organizaton_opcountry'));
var_dump($queryresult->getOrganizaton_opcountry());
//$queryresult->addOrganizaton_opcountry();
if ($form->isValid()) {
// Security request
if ($this->isAllowed('admin_res','admin_priv')) {
$form->bindValues();
$this->getEntityManager()->persist($queryresult);
$this->getEntityManager()->flush();
}
//echo "<script>window.close();</script>";
}
}
I am afraid, that i just missed a point. Though the post var_dump($this->request->getPost('organizaton_opcountry')); in the controller does output the following, after adding a third element and submitting:
array
0 =>
array
'id' => string '1' (length=1)
'country' => string 'Chad' (length=4)
1 =>
array
'id' => string '2' (length=1)
'country' => string 'Bermuda' (length=7)
2 =>
array
'id' => string '' (length=0)
'country' => string '(Not Specified)' (length=15)
Maybe you guys have an idea, or you have had the same problem before.
Thank you very much for any hint.
Kind regards,
David
Maybe u take a look at:
Saving a Doctine 2 Entity that contains an ObjectSelect element using Zend Form
Check the inputFilter in the Fieldset and add an inputfilter for the fieldset in the form e.g.:
$this->setValidationGroup(array(
'User' => array(
'name',
'role' // <- Fieldset
)
));
So i got a ZF2 application, got a Form and a InputFilter in the InputFilter i have:
$this->add(
array(
'name' => 'email',
'required' => true,
'validators' => array(
array(
'name' => 'EmailAddress'
),
array(
'name' => 'DoctrineModule\Validator\NoObjectExists',
'options' => array(
'object_repository' => $sm->get('doctrine.entitymanager.orm_default')->getRepository('YrmUser\Entity\User'),
'fields' => 'email'
),
),
),
)
);
works great, however when i edit a existing object and save it the NoObjectExists validator says a matching object is found so it doesn't validate.
Is there a solution to this problem?
Or should i just remove the validator on the edit form and catch the exception when a duplicate is inserted?
UPDATE:
How to use DoctrineModule\Validator\NoObjectExists in edit forms - Zend Framework 2 & Doctrine 2
is the same issue but the answer is to just remove the validator on editing, this off-course is not a solution. As you would still have to catch the exception thrown for when inserting a duplicate. I could do that no problem but what im asking for is a solution to make it work WITH NoObjectExists (otherwise whats the use of this validator if i have to catch the exception for duplicates anyway)
UPDATE, added other relevant code (my form and entity have more fields than this but i removed them to keep it readable on here)
FORM:
namespace YrmUser\Form;
use Zend\Form\Form;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use DoctrineORMModule\Stdlib\Hydrator\DoctrineEntity;
use YrmUser\Entity\User;
class UserForm extends Form
{
protected $objectManager;
/**
* __construct description
*
* #param String $name form name
*
* #return void
*/
public function __construct($name = null)
{
parent::__construct('new-user');
}
public function init()
{
$this->setHydrator(
new DoctrineHydrator($this->objectManager, 'YrmUser\Entity\User')
)->setObject(new User());
$this->setAttribute('method', 'post');
$this->add(
array(
'name' => 'email',
'attributes' => array(
'type' => 'email',
'placeholder' =>'Email',
),
'options' => array(
'label' => 'Email',
),
)
);
}
}
FILTER:
class UserFilter extends InputFilter
{
/**
* [__construct description]
*
* #param ServiceLocator $sm servicelocator
*/
public function __construct($sm)
{
$this->add(
array(
'name' => 'email',
'required' => true,
'validators' => array(
array(
'name' => 'EmailAddress'
),
array(
'name' => 'DoctrineModule\Validator\NoObjectExists',
'options' => array(
'object_repository' => $sm->get('doctrine.entitymanager.orm_default')->getRepository('YrmUser\Entity\User'),
'fields' => 'email'
),
),
),
)
);
}
}
CONTROLLER ACTION:
public function editAction()
{
$id = (int) $this->params('id', null);
if (null === $id) {
return $this->redirect()->toRoute('manage-users');
}
$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$formManager = $this->getServiceLocator()->get('FormElementManager');
$form = $formManager->get('UserForm');
$user = $em->find('YrmUser\Entity\User', $id);
$form->setInputFilter(new UserFilter($this->getServiceLocator()));
$form->bind($user);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$em->persist($user);
$em->flush();
return $this->redirect()->toRoute('manage-users');
}
}
return array(
'form' => $form,
'id' => $id
);
}
ENTITY:
class User
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", unique=true, length=255)
*/
protected $email;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param int $id user id
*
* #return void
*/
public function setId($id)
{
$this->id = (int) $id;
}
/**
* Get email.
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email.
*
* #param string $email user email adress
*
* #return void
*/
public function setEmail($email)
{
$this->email = $email;
}
}
thanks in advance,
Yrm
I lately had the same issue on my project, I spend lot of time searching for a solution and I've finally found this module LosBase.
It uses two customs validators which extend DoctrineModule\Validator\NoObjectExists : NoEntityExists for Add action and NoOtherEntityExists for Edit action.
So I used this appraoch to resolve my problem. This is the solution I've made so far :
NoOtherEntityExists validator :
use Zend\Validator\Exception\InvalidArgumentException;
use DoctrineModule\Validator\NoObjectExists;
class NoOtherEntityExists extends NoObjectExists
{
private $id; //id of the entity to edit
private $id_getter; //getter of the id
private $additionalFields = null; //other fields
public function __construct(array $options)
{
parent::__construct($options);
if (isset($options['additionalFields'])) {
$this->additionalFields = $options['additionalFields'];
}
$this->id = $options['id'];
$this->id_getter = $options['id_getter'];
}
public function isValid($value, $context = null)
{
if (null != $this->additionalFields && is_array($context)) {
$value = (array) $value;
foreach ($this->additionalFields as $field) {
$value[] = $context[$field];
}
}
$value = $this->cleanSearchValue($value);
$match = $this->objectRepository->findOneBy($value);
if (is_object($match) && $match->{$this->id_getter}() != $this->id) {
if (is_array($value)) {
$str = '';
foreach ($value as $campo) {
if ($str != '') {
$str .= ', ';
}
$str .= $campo;
}
$value = $str;
}
$this->error(self::ERROR_OBJECT_FOUND, $value);
return false;
}
return true;
}
}
NoEntityExists validator :
use Zend\Validator\Exception\InvalidArgumentException;
use DoctrineModule\Validator\NoObjectExists;
class NoEntityExists extends NoObjectExists
{
private $additionalFields = null;
public function __construct(array $options)
{
parent::__construct($options);
if (isset($options['additionalFields'])) {
$this->additionalFields = $options['additionalFields'];
}
}
public function isValid($value, $context = null)
{
if (null != $this->additionalFields && is_array($context)) {
$value = (array) $value;
foreach ($this->additionalFields as $field) {
$value[] = $context[$field];
}
}
$value = $this->cleanSearchValue($value);
$match = $this->objectRepository->findOneBy($value);
if (is_object($match)) {
if (is_array($value)) {
$str = '';
foreach ($value as $campo) {
if ($str != '') {
$str .= ', ';
}
$str .= $campo;
}
$value = $str;
}
$this->error(self::ERROR_OBJECT_FOUND, $value);
return false;
}
return true;
}
}
Using this validators with inputFilter :
In my custom input filters, I added two methods : one to append the NoEntityExists validator, and the other to append the NoOtherEntityExists validator :
/**
* Appends doctrine's NoObjectExists Validator for Add FORM .
*
* #param \Doctrine\ORM\EntityRepository $repository
* #return \Zend\InputFilter\InputFilter
*/
public function appendAddValidator(EntityRepository $repository)
{
$this->add($this->getFactory()->createInput( array(
'name' => 'libellesite', //unique field name
'validators' => array(
array(
'name' => 'Netman\Form\NoEntityExists',//use namespace
'options' => array(
'object_repository' => $repository,
'fields' => 'libellesite',
'messages' => array(
'objectFound' => 'custom message here'
),
),
),
)
)));
return $this;
}
/**
* Appends doctrine's NoObjectExists Validator for EDIT FORM.
*
* #param \Doctrine\ORM\EntityRepository $repository
* #return \Zend\InputFilter\InputFilter
*/
public function appendEditValidator(EntityRepository $repository, $id)
{
$this->add($this->getFactory()->createInput( array(
'name' => 'libellesite',
'validators' => array(
array(
'name' => 'Netman\Form\NoOtherEntityExists',
'options' => array(
'object_repository' => $repository,
'fields' => 'libellesite',
'id'=>$id, //
'id_getter'=>'getCodesite',//getter for ID
'messages' => array(
'objectFound' => 'custom message here'
),
),
),
)
)));
return $this;
}
Controller :
In the addAction :
$repository = $em->getRepository('Entity\Name');
$form->setInputFilter($filter->appendAddValidator($repository));
In the editAction :
$id = $this->params('id', null);
$repository = $em->getRepository('Entity\Name');
$form->setInputFilter($filter->appendEditValidator($repository,$id));
I have a ManyToMany that I broke into OneToMany and ManyToOne relationship. I want to build a form that has checkboxes instead of collection, and I am using the 'DoctrineObject' hydrator, but it does not work and I don't know what is going wrong.
I removed from my code below all of the other not related fields.
Role Entity:
/**
* #orm\Entity
* #orm\Table(name="roles")
*/
class RolesEntity extends HemisEntity {
/**
* #orm\Id
* #orm\Column(type="integer");
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #orm\Column(name="role_code",type="string")
*/
protected $roleCode;
/**
* #orm\OneToMany(targetEntity="RolesPermissionsEntity", mappedBy="role", cascade={"persist"})
*/
protected $rolePermissions;
public function __construct()
{
$this->rolePermissions = new ArrayCollection();
}
public function setRolePermissions($rolePermissions)
{
$this->rolePermissions = $rolePermissions;
return $this;
}
public function addRolePermissions(Collection $rolePermissions)
{
foreach ($rolePermissions as $rolePermission) {
$rolePermission->setRole($this);
$this->rolePermissions->add($rolePermission);
}
}
public function removeRolePermissions(Collection $rolePermissions)
{
foreach ($rolePermissions as $rolePermission) {
$rolePermission->setRole(null);
$this->rolePermissions->removeElement($rolePermission);
}
}
public function getRolePermissions()
{
return $this->rolePermissions;
}
}
The ManyToMany table entity (it has more fields and so I broke it):
/**
* #orm\Entity
* #orm\Table(name="roles_permissions")
*/
class RolesPermissionsEntity extends HemisEntity {
/**
* #orm\Id
* #orm\Column(type="integer");
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #orm\ManyToOne(targetEntity="RolesEntity", inversedBy="rolePermissions")
* #orm\JoinColumn(name="role_id", referencedColumnName="id")
**/
protected $role;
/**
* #orm\ManyToOne(targetEntity="PermissionsEntity", inversedBy="permissionRoles")
* #orm\JoinColumn(name="permission_id", referencedColumnName="id")
**/
protected $permission;
public function setRole($role)
{
$this->role = $role;
return $this;
}
public function getRole()
{
return $this->role;
}
public function setPermission($permission)
{
$this->permission = $permission;
return $this;
}
public function getPermission()
{
return $this->permission;
}
}
My form look like this:
class RoleForm extends Form implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('role');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new RolesEntity());
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'roleCode',
'options' => array(
'label' => 'Role Code'
),
));
$this->add(array(
'name' => 'rolePermissions',
'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
'options' => array(
'label' => 'Permissions',
'object_manager' => $objectManager,
'target_class' => 'Hemis\Fnd\PermissionsEntity',
'property' => 'permissionDesc'
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Submit',
),
));
}
public function getInputFilterSpecification()
{
return array(
'roleCode' => array(
'required' => false
),
'rolePermissions' => array(
'required' => true
)
);
}
}
The problem is that when I dump the $role it does not contains any rolePermissions and even that they are passed from the form they are just not hydrated into the object. I hope that my question is clear.
Any idea about what is wrong with my code or there is a better way to do that using checkboxes?
class RoleForm extends Form implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
// ...
$this->add(array(
'name' => 'rolePermissions',
'type' => 'Zend\Form\Element\Collection',
'options' => array(
'label' => 'Role Permissions',
'count' => 0,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type' => 'Zend\Form\Fieldset',
'options' => array(
'use_as_base_fieldset' => true
),
'elements' => array(
// add form fields for the properties of the RolesPermissionsEntity class here
array(
'name' => 'id',
'type' => 'Zend\Form\Element\Hidden',
),
array(
'name' => 'role',
'type' => 'Zend\Form\Element\Checkbox',
// other options
),
// ...
),
),
),
));
// ...
}
// ...
}