I have a form, used for a course subscription, in which I have 2 entity fields, activite and etudiant. I would like NOT to validate this form IF the trainer i already booked (information that i can find in the DB through the entity activite).
How (where...) can i add some logic instructions to control the validation of this form?
Is anybody has an idea? A lead? It would be so simple WITHOUT Symfony (for me)!...
Thanks
class InscriptionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('activiteId', 'entity',
array('label'=>'Activité',
'attr'=>array('class'=>'form-control'),
'class'=>'AssoFranceRussie\MainBundle\Entity\Activite',
'property'=>'nomEtNiveauEtJour',
))
->add('etudiantId', 'entity',array('label'=>'Etudiant',
'attr'=>array('class'=>'form-control'),
'class'=>'AssoFranceRussie\MainBundle\Entity\Etudiant',
'property'=>'NomEtPrenom',
))
;
}
You can write your own constraints and validators by extending the Symfony validation classes.
You need to extend Symfony\Component\Validator\Constraint to define the constraint and Symfony\Component\Validator\ConstraintValidator to define the validation code.
There are probably other ways to do this as well, but this gives you complete control of the validation.
You could do what you want in this way:
1- You need a variable to store the EntityManager in your InscriptionType class:
protected $em;
public function __construct($em) {
$this->em = $em;
}
2- Pass the entity manager to the FormType class from your controller as below:
new InscriptionType( $this->getDoctrine()->getManager() );
3- Add the logic what you want in the setDefaultOptions function to specify the validation_groups what you want for the form:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$p = $this->em->getRepository('YourBundle:YourEntity')->find(1);
if($p){
$resolver->setDefaults(array(
'data_class' => 'YourBundle\Entity\YourEntity',
'validation_groups' => array('myValidation1'),
'translation_domain'=>'custom'
));
}
else{
$resolver->setDefaults(array(
'data_class' => 'YourBundle\Entity\YourEntity',
'validation_groups' => array('myValidation2'),
'translation_domain'=>'custom'
));
}
}
4- In your entity, you need to specify the validation groups for the fields of the entity:
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\NotNull(groups={"myValidation1"})
*/
private $name;
/**
* #var date
*
* #ORM\Column(name="start", type="date")
* #Assert\NotNull(groups={"myValidation1", "myValidation2"})
* #Assert\Date()
*/
private $start;
In this case, the field 'start' would be validated in both cases, but the first only with the myValidation1 is the group to be validated.
In this way, you could control which fields you want to validate.
Related
Symfony version : 2.8.5
Context: I have an entity Restaurant which has a OneToOne relationship with an entity Coordinates which have several relations with other entities related to Coordinates informations. I my backend I create a form related to Restaurant entity with a custom nested form related to Coordinates.
Nota : I use EasyAdminBundle to generate my backend.
Entities relations scheme :
Restaurant
1 ________ 1 `Coordinates`
* ________ 1 `CoordinatesCountry`
1 ________ 1 `CoordinatesFR`
* ________ 1 `CoordinatesFRLane`
* ________ 1 `CoordinatesFRCity`
Backend view :
At this point I try the following scenario :
I create a new Restaurant, so I fill the fields related form for the first time. I let the Coordinates nested form blank (empty fields). So after form submission, validation messages are displayed (see image below).
I edit the previous form and this time I fill the fields of the Coordinates nested form. After form submission, a new Coordinates entity is hydrated and a relationship is created between Restaurant and Coordinates.
Once again I edit the previous form and this time I clear all the fields of the Coordinates nested form. The validation is not triggered and I get the following error :
Expected argument of type "FBN\GuideBundle\Entity\CoordinatesFRCity",
"NULL" given
I precise that in CoordinatesFRType (see code below), to trigger the validations message the first time I had to use the option empty_data with a closure (like described in the official doc) to instatiate a new CoordinatesFR instance in case of empty datas (all fields blank). But here, in this article (written by the creator of the Symfony form component), it is explained (see empty_data and datta mappers paragraphs) that the empty_data is only called at object creation. So I think this the reason why my validation does not work anymore in case of edition.
Question : why the validation is not effective anymore when editing my form and clearing all embedded form ?
The code (only what is necessary) :
Restaurant entity
use Symfony\Component\Validator\Constraints as Assert;
class Restaurant
{
/**
* #ORM\OneToOne(targetEntity="FBN\GuideBundle\Entity\Coordinates", inversedBy="restaurant", cascade={"persist"})
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
* #Assert\Valid()
*/
private $coordinates;
}
Coordinates entity
use Symfony\Component\Validator\Constraints as Assert;
class Coordinates
{
/**
* #ORM\ManyToOne(targetEntity="FBN\GuideBundle\Entity\CoordinatesCountry")
* #ORM\JoinColumn(nullable=false)
*/
private $coordinatesCountry;
/**
* #ORM\OneToOne(targetEntity="FBN\GuideBundle\Entity\CoordinatesFR", inversedBy="coordinates", cascade={"persist"})
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
* #Assert\Valid()
*/
private $coordinatesFR;
/**
* #ORM\OneToOne(targetEntity="FBN\GuideBundle\Entity\Restaurant", mappedBy="coordinates")
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $restaurant;
}
CoordinatesFR entity
use Symfony\Component\Validator\Constraints as Assert;
class CoordinatesFR extends CoordinatesISO
{
/**
* #ORM\ManyToOne(targetEntity="FBN\GuideBundle\Entity\CoordinatesFRLane")
* #ORM\JoinColumn(nullable=true)
* #Assert\NotBlank()
*/
private $coordinatesFRLane;
/**
* #ORM\ManyToOne(targetEntity="FBN\GuideBundle\Entity\CoordinatesFRCity")
* #ORM\JoinColumn(nullable=false)
* #Assert\NotBlank()
*/
private $coordinatesFRCity;
/**
* #ORM\OneToOne(targetEntity="FBN\GuideBundle\Entity\Coordinates", mappedBy="coordinatesFR")
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $coordinates;
}
Easy Admin config (equivalent to RestaurantType)
easy_admin:
entities:
Restaurant:
class : FBN\GuideBundle\Entity\Restaurant
form:
fields:
- { property: 'coordinates', type: 'FBN\GuideBundle\Form\CoordinatesType' }
CoordinatesType
class CoordinatesType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('CoordinatesCountry', EntityType::class, array(
'class' => 'FBNGuideBundle:CoordinatesCountry',
'property' => 'country',
))
->add('coordinatesFR', CoordinatesFRType::class)
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FBN\GuideBundle\Entity\Coordinates',
));
}
}
CoordinatesFRType
class CoordinatesFRType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('laneNum', TextType::class)
->add('coordinatesFRLane', EntityType::class, array(
'class' => 'FBNGuideBundle:CoordinatesFRLane',
'property' => 'lane',
'placeholder' => 'label.form.empty_value',
))
->add('laneName', TextType::class)
->add('miscellaneous', TextType::class)
->add('locality', TextType::class)
->add('metro', TextType::class)
->add('coordinatesFRCity', EntityType::class, array(
'class' => 'FBNGuideBundle:CoordinatesFRCity',
'property' => 'display',
'query_builder' => function (CoordinatesFRCityRepository $repo) {
return $repo->getAscendingSortedCitiesQueryBuilder();
},
'placeholder' => 'label.form.empty_value',
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FBN\GuideBundle\Entity\CoordinatesFR',
// Ensures that validation error messages will be correctly displayed next to each field
// of the corresponding nested form (i.e if submission and CoordinatesFR nested form with all fields empty)
'empty_data' => function (FormInterface $form) {
return new CoordFR();
},
));
}
}
Generated Entities from existing database
Generated CRUD controller
But it does not work with exception message:
Entities passed to the choice field must be managed. Maybe persist them in the entity manager?
Entity
/**
* Question
*
* #ORM\Table(name="question", indexes={#ORM\Index(name="question_category_id", columns={"question_category_id"})})
* #ORM\Entity
*/
class Question
{
//...
/**
* #var \AppBundle\Entity\QuestionCategory
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\QuestionCategory")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="question_category_id", referencedColumnName="id")
* })
*/
private $questionCategory;
public function __construct()
{
$this->questionCategory = new QuestionCategory();
}
//...
}
Form
class QuestionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('questionCategory');
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Question'
));
}
}
Controller
class QuestionController extends Controller
{
//...
/**
* Creates a new Question entity.
* #Route("/new", name="question_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$question = new Question();
$form = $this->createForm('AppBundle\Form\QuestionType', $question);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($question);
$em->flush();
return $this->redirectToRoute('question_show', array('id' => $question->getId()));
}
return $this->render('question/new.html.twig', array(
'question' => $question,
'form' => $form->createView(),
));
}
//...
}
Deep debugging gives nothing to me. How to fix it?
Test repository to reproduce error: https://github.com/sectus/question.test.local
Beware, this error can also be raised when using 'by_reference' => false, in your form type with relations that are not ManyToMany.
An unfortunate copy/paste put me in this situation.
According to the code shown on your GitHub project, the Question entity has the following constructor:
public function __construct()
{
$this->questionCategory = new QuestionCategory();
}
When you create an entity form field, it can only contain values that are managed by doctrine, but your new questionCategory is not managed.
Usually, the best solution is just to not fill this entity field in the constructor, but only in those places you strictly need it. When building a form, Synfony will fill it for you after submitting and calling $form->handleRequest().
So, in your case, just remove the Question entity's constructor.
After that, you'll also need to implement the __toString() method in QuestionCategory entity:
public function __toString(){
return 'whatever you neet to see the type`;
}
In my case I was having this issue because I was using EntityType instead of ChoiceType, to build the selectList.
EntityType display only data from database, instead ChoiceType can display "not managed" objects.
I hope this will help.
This error means the attribute questionCategory which is a relationship, is not managed by the EntityManager. For this to be done automatically, add a cascade-persist in your Doctrine Mapping for questionCategory attribute:
Entity
/**
* Question
*
* #ORM\Table(name="question")
* #ORM\Entity
*/
class Question
{
//...
/**
* #ORM\ManyToOne(
* targetEntity="QualityBundle\Entity\QuestionCategory",
* cascade={"persist"}
* )
*/
private $questionCategory;
//...
}
This way, when you call $em->persist($question);, the QuestionCategory linked to your Question will automatically be persisted as well.
There are different reasons that create this issue.
In my case, I fixed it changing
by_reference' => false
to
by_reference' => true
in the CRUD controller.
In my case, it just was because by my fault I was using the QueryManager instead of EntityManager to find the entity in my controller.
I have entity developer and entity skill, skill have ManyToMany with Platforms, Language and Speciality and I need create form for developer, developer can selected skills and when selected some skill developer can selected Platforms, Language and Speciality for this skill. If developer selected two skill or more so have more Platforms, Language and Speciality for selected. And I don't know how this is create in Symfony. Now I create form only selected skills
class DeveloperProfessionalSkillsType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name');
$builder->add('skills','entity',
array(
'class'=>'Artel\ProfileBundle\Entity\Skill',
'property'=>'skill',
'multiple'=>true,
)
);
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Artel\ProfileBundle\Entity\Developer',
'validation_groups' => array('professional_skills')
));
}
/**
* #return string
*/
public function getName()
{
return 'developer_professional_skills';
}
but now I have error form is not valid, interesting when I add 'expanded' => true, all work fine, but I don't need expanded I need simple selected field:
this is my entity
class Skill
{
/**
* #ORM\ManyToMany(targetEntity="Artel\ProfileBundle\Entity\Skill", mappedBy="skills", cascade={"persist"})
*/
protected $developers;
/**
* #var \Artel\ProfileBundle\Entity\CodeDirectoryProgramLanguages
*
* #ORM\ManyToMany(targetEntity="CodeDirectoryProgramLanguages", inversedBy="skills", cascade={"persist"})
*/
protected $language;
/**
* #var \Artel\ProfileBundle\Entity\CodeDirectoryPlatforms
*
* #ORM\ManyToMany(targetEntity="CodeDirectoryPlatforms", inversedBy="skills", cascade={"persist"})
*/
protected $platforms;
/**
* #var \Artel\ProfileBundle\Entity\CodeDirectorySpecialities
*
* #ORM\ManyToMany(targetEntity="CodeDirectorySpecialities", inversedBy="skills", cascade={"persist"})
*/
protected $specialities;
and my action
public function submitProfessionalSkillsAction($securitytoken)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new DeveloperProfessionalSkillsType(), $user->getDeveloper());
$form->handleRequest($request);
if ($form->isValid()) {
$em->flush();
Recommend, please, how best to solve this problem
Instead of
$builder->add('skills','entity',
array(
'class'=>'Artel\ProfileBundle\Entity\Skill',
'property'=>'skill',
'multiple'=>true,
)
);
You can create new form and add it to your current form like this:
$builder->add('skills', new SkillsType()
);
And in new form you can define all your fields like:
$builder->add('language','entity',
array(
'class'=>'Artel\ProfileBundle\Entity\Language',
'property'=>'some_property',
'multiple'=>true,
)
);
if you need many skills you can use collection form type:
->add('skills', 'collection', array('type' => new SkillsType(),
'allow_add' => true,'by_reference' => false))
So I'm trying to create a registration form in Symfony 2 which contains my "Person" entity. The person entity has a one-to-many join, and I want the registration form to allow the user to select a single instance of this "Many" side of the join.
The structure is Users and Institutions. A user can have many institutions. I want a user to select a single institution at registration time (but the model allows for more later).
The basic structure is:
RegistrationType -> PersonType -> PersonInstitutionType
…with corresponding models:
Registration (simple model) -> Person (doctrine entity) -> PersonInstitution (doctrine entity, oneToMany relation from Person)
I tried to pre-populate an empty Person & PersonInstitution record in the RegistrationController but it gives me the error:
Expected argument of type "string or Symfony\Component\Form\FormTypeInterface", "TB\CtoBundle\Entity\PersonInstitution" given
(ok above has been fixed).
I've moved the code from my website to here below, trying to remove all the irrelevant bits.
src/TB/CtoBundle/Form/Model/Registration.php
namespace TB\CtoBundle\Form\Model;
use TB\CtoBundle\Entity\Person;
class Registration
{
/**
* #var Person
*/
private $person
private $termsAccepted;
}
src/TB/CtoBundle/Form/RegistrationType.php
namespace TB\CtoBundle\Form;
use TB\CtoBundle\Form\PersonType;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('person', new PersonType());
$builder->add('termsAccepted','checkbox');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'TB\CtoBundle\Form\Model\Registration',
'cascade_validation' => true,
));
}
public function getName()
{
return 'registration';
}
}
src/TB/CtoBundle/Entity/Person.php
namespace TB\CtoBundle\Entity;
use TB\CtoBundle\Entity\PersonInstitution
/**
* #ORM\Entity()
*/
class Person
{
/**
* #var ArrayCollection
* #ORM\OneToMany(targetEntity="PersonInstitution", mappedBy="person", cascade={"persist"})
*/
private $institutions;
}
src/TB/CtoBundle/Form/PersonType.php
namespace TB\CtoBundle\Form;
class PersonType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('institutions', 'collection', array('type' => new PersonInstitutionType()))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'TB\CtoBundle\Entity\Person',
));
}
/**
* #return string
*/
public function getName()
{
return 'tb_ctobundle_person';
}
}
src/TB/CtoBundle/Entity/PersonInstitution.php
namespace TB\CtoBundle\Entity
/**
* PersonInstitution
*
* #ORM\Table()
* #ORM\Entity
*/
class PersonInstitution
{
/**
* #ORM\ManyToOne(targetEntity="Person", inversedBy="institutions", cascade={"persist"})
*/
private $person;
/**
* #ORM\ManyToOne(targetEntity="Institution", inversedBy="members")
*/
private $institution;
/**
* #ORM\Column(type="boolean")
*/
private $approved;
}
src/TB/CtoBundle/Form/PersonInstititionType.php
namespace TB\CtoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PersonInstitutionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('approved')
->add('person')
->add('institution')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'TB\CtoBundle\Entity\PersonInstitution'
));
}
/**
* #return string
*/
public function getName()
{
return 'tb_ctobundle_personinstitution';
}
}
src/TB/CtoBundle/Controller/Registration.php
namespace TB\CtoBundle\Controller;
class RegisterController extends Controller
{
/**
*
* #param Request $request
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function registerAction(Request $request)
{
$registration = new Registration;
$person = new Person();
$institution = new PersonInstitution();
$person->addInstitution($institution);
$registration->setPerson($person);
// this causes error:
// Entities passed to the choice field must be managed. Maybe persist them in the entity manager?
// $institution->setPerson($person);
$form = $this->createForm(new RegistrationType(), $registration);
$form->handleRequest($request);
if($form->isValid()) {
$registration = $form->getData();
$person = $registration->getPerson();
// new registration - account status is "pending"
$person->setAccountStatus("P");
// I'd like to get rid of this if possible
// for each "PersonInstitution" record, set the 'person' value
foreach($person->getInstitutions() as $rec) {
$rec->setPerson($person);
}
$em = $this->getDoctrine()->getManager();
$em->persist($person);
$em->flush();
}
return $this->render('TBCtoBundle:Register:register.html.twig', array('form' => $form->createView()));
}
}
Here is a detailed solution for adding an Collection field to Person entity and formType.
Your complex question with Registration entity can be solved with this.
I suggest you to use this 3 entity related connection if it is really needed. (only because of termsAccepted data!?)
If you won't change your opinion, then use this annotation:
Registration code:
use TB\CtoBundle\Entity\Person;
/**
* #ORM\OneToOne(targetEntity="Person")
* #var Person
*/
protected $person;
Person code:
use TB\CtoBundle\Entity\PersonInstitution;
/**
* #ORM\OneToMany(targetEntity="PersonInstitution", mappedBy = "person")
* #var ArrayCollection
*/
private $institutions;
/* I suggest you to define these functions:
setInstitutions(ArrayCollection $institutions),
getInstitutions()
addInstitution(PersonInstitution $institution)
removeInstitution(PersonInstitution $institution)
*/
PersonInstitution code:
use TB\CtoBundle\Entity\Person;
/**
* #ORM\ManyToOne(targetEntity="Person", inversedBy="institutions", cascade={"persist"}))
* #var Person
*/
private $person;
PersonType code:
use TB\CtoBundle\Form\PersonInstitutionType;
->add('institutions', 'collection', array(
'type' => new PersonInstitutionType(), // here is your mistake!
// Other options can be selected here.
//'allow_add' => TRUE,
//'allow_delete' => TRUE,
//'prototype' => TRUE,
//'by_reference' => FALSE,
));
PersonController code:
use TB\CtoBundle\Entity\Person;
use TB\CtoBundle\Entity\PersonInstitution;
/**
* ...
*/
public funtcion newAction()
{
$person = new Person;
$institution = new PersonInstitution;
$institution->setPerson($person);
$person->addInstitution($institution);
$form = $this->createForm(new PersonType($), $person); // you can use formFactory too.
// If institution field is required, then you have to check,
// that is there any institution able to chose in the form by the user.
// Might you can redirect to institution newAction in that case.
return array( '...' => $others, 'form' => $form);
}
If you need more help in twig code, then ask for it.
I want to handle all validations with #Assert so I'm using Models for my web forms (Form Type) which are not mapped to database. The question I have is, is it an acceptable practise in Symfony world?
I know that one disadvantage of this way is not being able to automatically generate setters and getters. I read up on it but didn't get a clear picture so that's why I'm asking.
A rough example:
LoginType.php
namespace User\RecordBundle\Resources\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class LoginType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAction($options['action'])
->setMethod('POST')
->add('username', 'text', array('label' => 'Username'))
->add('button', 'submit', array('label' => 'Login'));
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array('data_class' => 'User\RecordBundle\Entity\UserEntity'));
}
/**
* Returns the name of this type.
*
* #return string The name of this type
*/
public function getName()
{
return 'login';
}
}
LoginModel.php
namespace User\RecordBundle\Resources\Form\Model;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class LoginModel
* Mapped to Login form
*
* #package User\RecordBundle\Resources\Form\Model
*/
class LoginModel
{
/**
* #Assert\NotBlank(message = "The Username field should not be blank.")
*
* #var string $username
*/
protected $username;
/**
* #return string $username
*/
public function getUsername()
{
return $this->username;
}
/**
* #param string $username
* #return $this
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
}
This case: your FormType is not related to any Entity, must be rare in a well planned application. So rarely Model with FormType solution can be used, I don't have any objections to it. Remark: Specifically for User handling I recommend you to use friends of symfony created: FOS\UserBundle\FOSUserBundle().
You said that you're new in Symfony, so I summarized here the general practice of making a Form, which is related to an Entity and user will be available to fill some part of it.
class code:
class Entity
{
/**
* #Assert\NotBlank(message = "The data is empty.")
*/
private $data;
}
form type code:
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
class EntityType extends AbstractType
{
/**
* #var \Doctrine\Common\Persistence\ObjectManager
*/
protected $om;
protected $admin;
protected $edit;
public function __construct($om, $admin = false, $new = false)
{
$this->om = $om;
$this->admin = $admin;
$this->new = $;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// You can show specific parts of the Entity for the admin to fill and reduced group of fields for the common user.
// You can set specific behaviour in case of creation and editing.
// You can add a collection type field, and select specific entities with ObjectManager. To make your form more flexible.
$builder
->add('data', 'text', array(
'label' => 'Data text',
'label_attr' => array(
'class' => 'reqfield'
),
'attr' => array(
'class' => 'css-class-of-the-field'
'...' => $etc,
))
// You don't need to add submit button
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Application\EntityBundle\Entity\Entity'
));
}
public function getName()
{
return 'application_entity_bundle_entity';
}
}
// Actions like: new and edit, can use your formType above.