Repeated field not validating in symfony2 - symfony

//-- this is my controller code------
$form = $this->createFormBuilder()
->add('curpass', 'password')
->add('password', 'repeated', array(
'type' => 'password',
'first_name' => " new Password",
'second_name' => "Re-enter Password",
'invalid_message' => 'The password fields must match.'
))
->getForm();
//----this is my twig code-----
<form action="#" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" />
</form>
Can you suggest me what is wrong in my code? It is not comparing both password field 'new Password' and 'Re-enter Password'.

Have a read in the documentation:
This is the actual field name to be used for the first field. This is
mostly meaningless, however, as the actual data entered into both of
the fields will be available under the key assigned to the repeated
field itself (e.g. password). However, if you don't specify a label,
this field name is used to "guess" the label for you.
This means you cannot set the label using the first_name and second_name but you have to use options and passing an array with the label. I didn't found any solution to change the label of the second field though.
Try removing the first_name and second_name and see if it works.

Related

Get checkbox value of own made form type in Symfony

I have added the following form typo in Symfony to my form. As it is not a member of the entity I need to handle it manually in the controller. How can i get the checkbox value in my controller?
->add('showUrl', 'checkbox', array(
'mapped' => false,
))
This is the generated html in the form:
<input type="checkbox" id="cuslocation_accountreg_showUrl" name="cuslocation[accountreg][showUrl]" required="required" value="1">
$form->getData()['showUrl']
or
$form->get('showUrl')->getData()
or
$form['showUrl']->getData()

Why getMethod() returns "GET" instead of "POST"?

The goal is to submit a POST form with two radiobuttons (tipo) and a text field (numero) to make a query in my DB and show the data to the user.
I am trying to submit the form below, however when I submit the form, the request coming accross is a 'GET REQUEST'. The form is in "SupuestoConfig.html.twig":
<div id="cuadro">
<form id="configurador" action="{{ path('configsup') }}" method="POST">
<p class="titulo_configurador">Elija supuesto penal:</p>
{{ form_row(form.tipo) }}
{{ form_row(form.numero, { 'label' : ' ', 'attr' : { 'class' : 'rec3' }}) }}
{{ form_rest(form) }}
<input type="submit" name="cargar" value="Cargar" class="inputbt"/>
</form>
</div>
I render the previous form in "principal.html.twig":
{{ render(controller('PprsBundle:Default:SupuestoConfig'), {'strategy': 'inline'}) }}
My "Controller.php":
/**
* #Route("/pprs/principal/supuesto={numero_supuesto}", name="configsup")
* #Template("PprsBundle:Default:SupuestoConfig.html.twig")
*/
public function SupuestoConfigAction($numero_supuesto = null)
{
$form = $this->createFormBuilder(null)
->add('tipo', 'choice', array(
'choices' => array(
'aleatorio' => 'Aleatorio',
'pornumero' => 'Por número'),
'multiple' => false,
'expanded' => true,
'data' => 'aleatorio'
))
// This add may contains error
->add('numero', 'text', array('label' => ' ','disabled' => true))
->getForm();
$peticion = $this->getRequest();
echo ('<script type="text/javascript">alert ("'.$peticion->getMethod().'");</script>');// Returns 'GET'
if ($peticion->isMethod('POST')) {
// Symfony2.2
$form->bind($peticion);
**$datos = $form->getData();**
*//foreach(array_keys($datos) as $p) {
//echo ('<script type="text/javascript">alert ("'.$datos.'");</script>');
//}*
if ($form->isValid()) { ... }
In Controller.php, despite I´ve got a GET request (when I remove the line
->add('numero', 'text',..
I´ve got a POST request, why is that?), in getData I don´t get the text field.
Finally, my routing.yml:
pprs_principal:
pattern: /pprs/principal/supuesto={numero_supuesto}/
defaults: { _controller: PprsBundle:Default:principal, numero_supuesto: 1 }
_pprs_principal:
pattern: /pprs/principal/
defaults: { _controller: FrameworkBundle:Redirect:redirect, route: pprs_principal }
Sorry for my bad english, Thanks in advance
Edit:
1) Anybody knows why I obtain a GET request instead of a POST when I add the text field in my createFormBuilder?
2) Anybody knows why Don't I get the text field when I call getData?
Help me please...
Maybe this answer could help you out:
getRequest() returns "GET" when posting form
Basically, when rendering a form with a {% render %} tag, it actually creates "another" request... It doesn't pass in the locale, the method, etc.
I opened a bug about this, and it went as By Design:
https://github.com/symfony/symfony/issues/7551

Symfony2 Forms: How do I create a collection of 'entity' forms

I have a one to many unidirectional relationship in my model. A User has one of many Status.
Using doctrine these are mapped as a unidirectional many-to-many with a unique constraint on one of the join columns.
I'd like to use a symfony form to select a status from the status table, submit the form and have symfony persist the relationship.
I've tried two approaches:
Using the Entity form type, however this produces an error (due to the many-to-many relationship doctrine expects to receive an instance of ArrayCollection rather than a single status object.
Using a collection entity objects. When using this approach an empty div with the id status is rendered in the form. Where as I expected a select box to appear containing status options.
Here is the code. Where am I wrong?
Entity code:
/**
* #ORM\ManyToMany(targetEntity="Status")
*/
protected $status;
Form type code:
$builder->add('status', 'collection', array(
'type' => 'entity',
'allow_add' => true,
'options' => array(
'class' => 'SunflyCoreBundle:Status',
'property' => 'name',
))
);
Form template code:
<form action="{{ path('_product_create_process') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" />
</form>
HTML Rendered on the page:
<div id="product_status" data-prototype="STUFF THAT WONT RENDER ON SO"></div>

symfony2 comparing hidden field with its hash with form validation

I would like to know how to compare fields in symfony2 form with custom validation.
In particular I want to compare a simple hidden field with its hash.
<input type="hidden" name="smoke" value="1" />
<input type="hidden" name="smoke_hash" value="kahsjkdasjkdh3iuy84932798" />
Something like "repeated Field" but validated with my own logic.
But more something like this:
use Symfony\Component\Validator\Constraints\HashMatchString;
$builder
->add('smoke', 'hidden', array(
'data' => 1,
)
)
->add('smoke_hash', 'hidden', array(
'constraints' => array(
new HashMatchString('smoke')
),
)
)
;
Form Goodness in Symfony 2.1
I’ve already see the solution of Steven Brown (http://www.yewchube.com/2011/08/symfony-2-field-comparison-validator/) but is one year ago with multiple touches on core files...
SOLVED
I’ve created a gist: Gist
Just add validation method to your entity http://symfony.com/doc/current/book/validation.html#getters

Drupal Custom Module / Form Question: Adding an array of fields

I'm creating a custom module where I'd like to have the "add another item" functionality for a particular field, but I can't seem to figure out what I need to do in order to accomplish this... I've been going through Drupal forums and their Forms API Reference, but I must not be getting something.... I'm using Drupal 6.20, and in my module, I tried:
$form['options'] = array(
'#title' => t('Options'),
'#type' => 'fieldset',
);
$form['options']['address'] = array(
'#type'=>'textfield',
'#title'=>t('Address'),
'#tree' => 1,
);
Thinking I would get an text input that looked like this:
<input type="text" class="form-text text" value="" size="60" id="edit-address-0-value" name="address[0][value]">
But, I just get an input that looks like this:
<input type="text" class="form-text" value="" size="60" id="edit-address" name="address" maxlength="128">
You need to set #tree on the element above the one you want to duplicate. FAPI will store values in a tree structure from that element on downwards.
To get a name like address[0][value] you will need something like
$form['options']['address'] = array(
'#tree' => TRUE,
);
$form['options']['address'][0] = array(
'#tree' => TRUE,
);
$form['options']['address'][0]['value'] = array(
'#type'=>'textfield',
'#title'=>t('Address'),
);
But you don't need the [value] part unless you are actually trying to achieve multi-valued grouped fields or if your field has a complex (custom) data type implemented with multiple PHP values (ie. latitude/longitude, start/stop dates, etc.).
You will also probably need to store the number of values in something like $form['options']['#nb_values'] or in an hidden field (if you plan to add the additional fields to the form using JavaScript).

Resources