2015-08-26 40 views
2

我已经试过四处寻找可能的解决方案,但没有运气。Symfony2形式 - 许多到许多作为文本导致错误

我所拥有的是属性和邮编之间的多对多关系,例如由于可能条目数量的限制,我无法在select中显示邮编。

我的解决方案是将它作为表单中的文本字段,然后在PrePersist上捕获它以搜索匹配的记录,然后在坚持数据库之前将其应用于实体。

问题是当表单验证它仍在尝试将字符串值传递给期望实体对象的setter时。

有没有办法防止这种错误?

我附上了我的表格代码给你。

感谢,

哈利

$propertyData = new PropertyData(); 
 

 
     $builder 
 
      ->add('reference') 
 
      ->add('listing_type', 'choice', array('choices' => $propertyData->getListingTypes())) 
 
      ->add('listing_status', 'choice', array('choices' => $propertyData->getStatusList())) 
 
      ->add('title') 
 
      ->add('house_number') 
 
      ->add('address_line_1') 
 
      ->add('address_line_2') 
 
      ->add('town', 'text', array('data_class'=> 'Minos\Bundle\PropertyBundle\Entity\UtilTown')) 
 
      ->add('county') 
 
      ->add('country') 
 
      ->add('council') 
 
      ->add('region') 
 
      ->add('postcode', 'text', array('data_class'=> 'Minos\Bundle\PropertyBundle\Entity\UtilPostcode')) 
 
      ->add('short_description') 
 
      ->add('long_description') 
 
      ->add('size_sq_ft') 
 
      ->add('floor_level') 
 
      ->add('property_age') 
 
      ->add('tenure_type', 'choice', array('choices' => $propertyData->getTenureTypes())) 
 
      ->add('garage') 
 
      ->add('num_living_rooms') 
 
      ->add('num_bathrooms') 
 
      ->add('num_bedrooms') 
 
      ->add('num_floors') 
 
      ->add('num_receptions') 
 
      ->add('property_type') 
 
      //->add('prices') 
 
     ;

回答

1

你需要一个data transformer处理表单之前,您输入的字符串转换为一个实体。

$builder 
    // ... 
     ->add('postcode', 'text', array(
      'data_class'=> 'Minos\Bundle\PropertyBundle\Entity\UtilPostcode' 
     )) 
    // ... 
    ; 

    $builder->get('postcode')->addModelTransformer(new CallbackTransformer(
     //Render an entity to a string to display in the text input 
     function($originalInput){ 
      $string = $originalInput->getPostcode(); 
      return $string; 
     }, 

     //Take the form submitted value and convert it before processing. 
     //$submittedValue will be the string because you defined 
     // it in the builder that way 
     function($submittedValue){ 
      //Do whatever to fetch the postcodes entity: 
      $postcodeEntity = $entityManager->find('AppBundle\postcodes', $submittedValue); 
      return $postcodeEntity; 
     } 
    )); 

这只是一个例子(我没有测试过),你需要改变一些东西来匹配你的实体的外观。

+0

嗨,谢谢 - 这正是我需要的...... lifesaver –