update/validate embedded forms before saving in symfony - php

I would like to validate an embedded form field before it gets saved in the database. Currently it will save an empty value into the database if the form field is empty. I'm allowing empty fields, but I want nothing inserted if the form field is empty.
Also quick question, how to alter field values before validating/saving an embedded form field?
$this->form->getObject works in the action, but $this->embeddedForm->getObject says object not found

I found a really easy solution. The solution is to override your Form's model class save() method manually.
class SomeUserClass extends myUser {
public function save(Doctrine_Connection $conn = null)
{
$this->setFirstName(trim($this->getFirstName()));
if($this->getFirstName())
{
return parent::save();
}else
{
return null;
}
}
}
In this example, I'm checking if the firstname field is blank. If its not, then save the form. If its empty, then we don't call save on the form.
I haven't been able to get the validators to work properly, and this is an equally clean solution.

Symfony gives you a bunch of hooks into the form/object saving process.
You can overwrite the blank values with null pre/post validation using by overriding the the doSave() or processValues() functions of the form.
You can read more about it here: http://www.symfony-project.org/more-with-symfony/1_4/en/06-Advanced-Forms#chapter_06_saving_object_forms

Related

How to avoid of writing back data from symfony form?

I want to create readonly hidden field. Now I have field that looks like this:
$builder
->add('question_category_id', HiddenType::class);
And entity has method:
public function getQuestionCategoryId() {
return $this->getQuestion()->getQuestionCategory()->getId();
}
After saving I got following error:
Neither the property "question_category_id" nor one of the methods "addQuestionCategoryId()"/"removeQuestionCategoryId()", "setQuestionCategoryId()", "questionCategoryId()", "__set()" or "__call()" exist and have public access in class "Entity\UnitQuestionAnswer".
I could add dummy method
public function setQuestionCategoryId($id) {
return $this;
}
but it is not right way.
How to create readonly hidden field, or avoid of writing back data from from into entity?
S2.8 has a read_only attribute which would do what you want but it has been removed in 3.0.
The disabled attribute should work. Just be aware that the value itself will not actually be submitted symfony.com/doc/current/reference/forms/types/… so if you are doing anything funky with the posted data then that could be a problem.
I suppose it's possible to fool around with the internals but that would be more trouble than it is worth.
Personally, given that my get method was added just for the form, I would just add a corresponding set method and move on.

How can I get the form data from the FOSUserBundle registration form?

I am using the FOSUserBundle and have overwritten the RegistrationController. When the form is submitted and valid, I want to get the email address the user entered in the registration form.
But I don't see any way to get it. As taken from the Symfony2 forms documentation, you can get form data like this:
$this->get('request')->request->get('name');
But the RegistrationController does not know the get() method (as it's not inherited from the Symfony2 controller entity). So I could go like this:
// Note the ...->container->...
$this->container->get('request')->request->get('name');
But this returns NULL. Now I try to get it from the $form.
// Does contain a lot of stuff, but not the entered email address
$form->get('email');
// Does also contain a lot of stuff, but not the desired content
$request->get('email');
$request->request('email');
// Throws error message: No method getData()
$request->getData();
Any idea?
It's really, really simple. You create a form with related entity. In FOSUserBundle you should have a RegistrationFormHandler, and in process method you've got:
$user = $this->createUser();
$this->form->setData($user);
if ('POST' === $this->request->getMethod()) {
$this->form->bind($this->request);
if ($this->form->isValid()) /**(...)**/
After the line $this->form->bind($this->request) every value in $user object is overwritten by data from form. So you can use $user->getEmail().
On the other hand you are able to get data directly from request, but not by the property name, but by form name. In FOSUserBundle registration form it is called fos_user_registration - you can find it in FOS/UserBundle/Form/Type/RegistrationFormType.php in getName method.
You get it by:
$registrationArray = $request->get('fos_user_registration');
$email = $registrationArray['email'];
If you were to use Controller as a Service (which should work with this), you could pass the RequestStack (sf >=2.4) in the constructor and do $this->request_stack->getCurrentRequest()->get();
My guess is that you are trying to get the POST data. You are trying to put the data in a form object I presume. I would recommend you to take a look at: http://symfony.com/doc/current/book/forms.html if you have a custom form.
As regarding to your question, the form is probably containing a name. If you want to have direct access to it instead of doing things in your form, you need to fetch it multilevel if directly via the true at $deep, get('registration_form_name[email]', null, true); You can also do $email = $request->get('registration_form_name')['email']; (if you have php 5.4+)

Symfony Adding and Dealing With Custom Form Fields

I am using Symfony with propel to generate a form called BaseMeetingMeetingsForm.
In MeetingMeetingsForm.class.php I have the following configure method:
public function configure() {
$this->useFields(array('name', 'group_id', 'location', 'start', 'length'));
$this->widgetSchema['invited'] = new myWidgetFormTokenAutocompleter(array("url"=>"/user/json"));
}
In MeetingMeetings.php my save method is simply:
public function save(PropelPDO $con = null) {
$this->setOwnerId(Meeting::getUserId());
return parent::save($con);
}
However propel doesn't know about my custom field and as such doesn't do anything with it. Where and how to I put in a special section that can deal with this form field, please be aware it is not just a simple save to database, I need to deal with the input specially before it is input.
Thanks for your time and advice,
You have to define a validator (and/or create your own). The validator clean() method returns the value that needs to be persisted.
In Doctrine (I don't know Propel) the form then calls the doUpdateObject() on the form, which in turns calls the fromArray($arr) function on the model.
So if it's already a property on your model you'll only need to create the validator. If it's a more complex widget, you'll need to add some logic to the form.

Processing Zend_Form dynamically generated elements

I need to create a form where the elements (texbox, select, ..) will be dynamically inserted. Right now I have created a empty Form file with just a hidden element and them in my controller I go inserting elements according to certain conditions.
My form file:
class Form_Questions extends Zend_Form {
public function __construct() {
parent::__construct($options);
$this->setName('Questions');
// Hidden Label for error output
$hiddenlabel = new Zend_Form_Element_Hidden('hiddenlabel');
$hiddenlabel->addDecorator(new Form_Decorator_HiddenLabel());
$this->addElements( array($hiddenlabel) );
}
}
In the controller I have something like:
...
$form = new Form_Questions();
$request = $this->getRequest();
if ($request->isPost())
{
$formData = $request->getPost();
if ($form->isValid($request->getPost()))
{
die(var_dump($form->getValues()));
}
}
else
{
//... add textbox, checkbox, ...
// add final submit button
$btn_submit = new Zend_Form_Element_Submit('submit');
$btn_submit->setAttrib('id', 'submitbutton');
$form->addElement($btn_submit);
$this->view->form = $form;
}
The form displays fine but the validation is giving me big trouble. My var_dump() only shows the hidden element that is staticly defined in the Form file. It does not save the dinamic elements so altought I can get them reading what's coming via POST, I can not do something like
$form->getValue('question1');
It behaves like if Zend uses the Form file to store the values when the submit happend, but since the elements are created dinamically they do not persist (either their values) after the post so I can not process them using the standar getValue() way.
I would appreciate any ideas on how to make them "live" til after the post so I can read them as in a normal form.
The form which you are calling isValid() and getValues() methods on is actually your "empty" form - you have instantiated it only a few lines up and haven't added any elements to it at that point.
Remember that POST only sends an array of fieldName => fieldValue type, it doesn't actually send a Zend_Form object.
It is difficult to suggest a new solution without knowing what you are trying to achieve. It is generally better to add all possible elements to your Zend_Form right away, and then only use the ones you need in the view scripts, i.e. echo $this->form->myField;. This will allow isValid() to process all the elements of the form.
It sounds like the form is dynamic in the sense that the questions come from a db, not in then sense that the user modifies the form itself to add new questions.
Assuming this is the case, then I wouldn't add the question fields in the controller. Rather, I'd pass the questions to the form in the constructor and then add the question fields and the validators in the form's init() method. Then in the controller, just standard isPost() and isValid() processing after that.
Or, if you are saying that the questions to be added to the form are somehow a consequence of the hidden label posted, then perhaps you need two forms and two actions: one for the hidden field form and another for the questions.
Ok, the simplest solution I came up with - to my case and considering the really of the code I am currently playing with was to load all the questions I need from the database using a method from my Model (something like fetchQuestions()), them in my controller I go throught the recordset and create the form elements according to the current question of the recordset.
The elements are stacked in an array that is passed to my Form constructor. In the form constructor I read the array and generate all the dynamic elements. I them just echoed the form to the view.
I have not seem why it would be a bad idea to override the Form constructor as I also could not use any of the set/get methods to pass this to my form.

Pre-load value into field in symfony form, getting error "Cannot Update form fields"

I have a form that is supposed to create a very simple new entry into the database. One of the fields in this table is related to another table. Specifically, there is an event that people attend, and I need to assign people to an event. Each event can have several people attending, and there can be several events.
When an admin user adds members to an event, I don't need them selecting the event on the actual form, this should be passed via the URL. e.g.
event/new/id/1
However, I am really struggling as to how to include that ID in the form. If I try and manually set the field value, I get the error Cannot Update Form Fields
e.g.
$this->['attendanceSuccess_id'] = 1;
If I try and hide the field:
$this->widgetSchema['attendanceSuccess_id'] = new sfWidgetFormInputHidden();
The form shows but obviously no value is passed and I get "that fields is required error"
This seems like a really simple and common thing to do, but I can't find any solutions! How can I pass a URL value into a form where the field points to another class?
Here's what I've done. Basically your form holds a hidden with the id, and your action gets it from the request and puts in into the form as an option. In the form you can also set the relationship to the Doctrine objects.
Your form should have something like (I don't know what your form should extend exactly since you are using Doctrine and mine was in Propel)
class SomethingForm extends BaseSomethingForm {
public function __construct($object = null, $options = array(), $CSRFSecret = null)
{
parent::__construct($object, $options, $CSRFSecret);
if (isset($options['person_id']))
{
$this->getObject()->setPersonId($options['person_id']);
$this->setDefault('person_id', $options['person_id']);
}
}
}
public function configure()
{
$this->setWidget('person_id', new sfWidgetFormInputHidden());
...more stuff...
}
Then your action says:
$this->form = new SomethingForm(null, array(
'person_id' => $request->getParameter('person_id')
));

Categories