2012-09-14 27 views
70

Controllo alcune convalide nel mio controller. E voglio aggiungere un errore a un elemento specifico del mio modulo in caso di errore. Il mio modulo:Aggiungi errore all'elemento del modulo Symfony 2

use Symfony\Component\Form\FormError; 

// ... 

$config = new Config(); 
$form = $this->createFormBuilder($config) 
     ->add('googleMapKey', 'text', array('label' => 'Google Map key')) 
     ->add('locationRadius', 'text', array('label' => 'Location radius (km)')) 
     ->getForm(); 

// ... 

$form->addError(new FormError('error message')); 

Il metodo addError() aggiunge errore al modulo, non all'elemento. Come posso aggiungere un errore all'elemento locationRadius?

risposta

145

Si può fare

$form->get('locationRadius')->addError(new FormError('error message')); 

Come elementi del modulo sono anche di tipo FormInterface.

+1

Grazie. Ha risolto il mio problema. – pltvs

+0

@ m2mdas, ottima risposta! Come lo traduciamo? perché una volta creata un'istanza FormError, non la tradurrà, ho ragione? Ho provato e non lo traduce, e penso che abbia senso. Come tradurrei un'istanza FormError? – Mick

+1

Ciao @Patt, mi dispiace per la risposta in ritardo. Il componente Validator si occupa della traduzione dei messaggi di violazione dei vincoli del modulo prima che i messaggi di errore vengano aggiunti al modulo. Per aggiungere errori personalizzati hai tradotto il messaggio come per altre stringhe, ad es., $ This-> get ('traduttore') -> trans ('messaggio di errore') ' –

5

OK ragazzi, ho un altro modo. È più complesso e solo per casi specifici.

Il mio caso:

Ho una forma e dopo invio inserisco i dati al server API. E anche gli errori che ho ricevuto dal server API.

formato errore del server API è:

array(
    'message' => 'Invalid postal code', 
    'propertyPath' => 'businessAdress.postalCode', 
) 

Il mio obiettivo è quello di ottenere una soluzione flessibile. Consente di impostare l'errore per il campo corrispondente.

$vm = new ViolationMapper(); 

// Format should be: children[businessAddress].children[postalCode] 
$error['propertyPath'] = 'children['. str_replace('.', '].children[', $error['propertyPath']) .']'; 

// Convert error to violation. 
$constraint = new ConstraintViolation(
    $error['message'], $error['message'], array(), '', $error['propertyPath'], null 
); 

$vm->mapViolation($constraint, $form); 

Questo è tutto!

NOTA! Il metodoaddError() esclude l'opzione error_mapping.


La mia forma (forma Indirizzo incorporato nella forma societaria):

impresa

<?php 

namespace Acme\DemoBundle\Form; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\Validator\Constraints; 

class Company extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('companyName', 'text', 
       array(
        'label' => 'Company name', 
        'constraints' => array(
         new Constraints\NotBlank() 
        ), 
       ) 
      ) 
      ->add('businessAddress', new Address(), 
       array(
        'label' => 'Business address', 
       ) 
      ) 
      ->add('update', 'submit', array(
        'label' => 'Update', 
       ) 
      ) 
     ; 
    } 

    public function getName() 
    { 
     return null; 
    } 
} 

Indirizzo

<?php 

namespace Acme\DemoBundle\Form; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\Validator\Constraints; 

class Address extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      // ... 
      ->add('postalCode', 'text', 
       array(
        'label' => 'Postal code', 
        'constraints' => array(
         new Constraints\NotBlank() 
        ), 
       ) 
      ) 
      ->add('town', 'text', 
       array(
        'label' => 'Town', 
        'constraints' => array(
         new Constraints\NotBlank() 
        ), 
       ) 
      ) 
      ->add('country', 'choice', 
       array(
        'label' => 'Country', 
        'choices' => $this->getCountries(), 
        'empty_value' => 'Select...', 
        'constraints' => array(
         new Constraints\NotBlank() 
        ), 
       ) 
      ) 
     ; 
    } 

    public function getName() 
    { 
     return null; 
    } 
} 
+0

dove posizioni questo codice? $ vm = new ViolationMapper(); –

+0

@vidyvideni , Azione del controller in cui verrà gestito il modulo di invio. Inoltre, è possibile modificare questo codice e spostarlo in un metodo separato – Jekis