2012-04-06 110 views
1

好吧,说实话。不喜欢symfony决定采用核心文件的一些决定,所以我试图覆盖它们。例如覆盖核心Symfony2组件

Symfony/Component/Form/Extension/Core/Type/FieldType.php

我试着去改变获取呈现的名称,如果一个FormView有父母,因为他们做一些很酷的字符串格式化......

我只是试图使它所以$fullName$id都是$form->getName();

public function buildView(FormView $view, FormInterface $form) 
    { 
     $name = $form->getName(); 

     if ($view->hasParent()) { 
      $parentId = $view->getParent()->get('id'); 
      $parentFullName = $view->getParent()->get('full_name'); 

      // Custom Logic 
      //$id = sprintf('%s_%s', $parentId, $name); 
      //$fullName = sprintf('%s[%s]', $parentFullName, $name); 
      $id = $form->getName(); 
      $fullName = $form->getName(); 
     } else { 
      $id = $name; 
      $fullName = $name; 
     } 

     $types = array(); 
     foreach ($form->getTypes() as $type) { 
      $types[] = $type->getName(); 
     } 

     $view 
      ->set('form', $view) 
      ->set('id', $id) 
      ->set('name', $name) 
      ->set('full_name', $fullName) 
      ->set('errors', $form->getErrors()) 
      ->set('value', $form->getClientData()) 
      ->set('read_only', $form->isReadOnly()) 
      ->set('required', $form->isRequired()) 
      ->set('max_length', $form->getAttribute('max_length')) 
      ->set('pattern', $form->getAttribute('pattern')) 
      ->set('size', null) 
      ->set('label', $form->getAttribute('label')) 
      ->set('multipart', false) 
      ->set('attr', $form->getAttribute('attr')) 
      ->set('types', $types) 
     ; 
    } 

回答

0

构建了一个辅助函数。

public function fixForm(\Symfony\Component\Form\FormView $form) 
{ 
    foreach($form as &$child) 
    { 
     $name = $child->get('full_name'); 
     $id = $child->get('id'); 
     $matches = array(); 
     preg_match('/^(?<form>.+)\[(?<ele>.+)\]/', $name, $matches); 
     if(isset($matches['ele'])) 
      $child->set('full_name', $matches['ele']); 
     $matches = array(); 
     preg_match('/^(?<first>.+)_(?<second>.+)/', $id, $matches); 
     if(isset($matches['second'])) 
      $child->set('id', $matches['second']); 
    } 
    return $form; 
} 

及其工作。只需要在需要修复表单时调用此项

+0

为什么downvote? – Ascherer 2014-06-20 00:22:39

1

我想你可以尝试的是建立你自己的表单类型。

你可以把你自己的表单类型添加到你的包中,你有一个像“TestBundle/Form/Type”类似的干净结构。

在此字段类型中,您可以进行所需的更改。

How can I make a custom field type in symfony2?

这是一个有益的帖子里介绍的热,使自定义字段类型。

它的一个简短提示,我希望你找到一个好的解决方案,可以告诉我们它的工作,以及如何解决它。

+0

不幸的是,我所做的更改需要针对每种字段类型进行。我想避免重写所有字段类型只是为了更改名称 – Ascherer 2012-04-08 19:51:18

+0

您是否想过在Twig中解决这个问题?有一些方法可以自定义表单并更改模板中的字段。 http://symfony.com/doc/current/cookbook/form/form_customization.html – Stony 2012-04-09 00:50:53

+0

就像我上面说过的那样,在树枝做它会要求我改变所有的'form_widget',并试图避免这种情况 – Ascherer 2012-04-09 02:29:11