2011-12-11 45 views
1

我在Symfony2中的項目有兩個實體「用戶」和「團隊」。 用戶可以有很多團隊,團隊可以有很多用戶。在一個多一次添加一條記錄到許多關係

現在我加入玩家隊伍的方式是通過一個選擇框(在它的所有用戶數據庫),用戶可以選擇多個用戶,然後單擊保存將其插入到數據庫中。

我想有兩個文本框,而不是一個選擇框,因爲我不喜歡登錄的用戶能夠看到所有可用的用戶(特別是當這個箱子會得到很長)

我怎樣才能做到這一點? 因此,2個文本框(我將添加一個jquery自動完成器)和一個保存按鈕,將2個用戶添加到團隊中。

Thx。

編輯:

<?php 

namespace Tennisconnect\DashboardBundle\Form\Type; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilder; 

class TeamType extends AbstractType 
{ 
    public function buildForm(FormBuilder $builder, array $options) 
    { 
     $builder 
      ->add('player_one', 'text', array('property_path' => false)) 
      ->add('player_two', 'text', array('property_path' => false)) 
     ; 
    } 

    public function getName() 
    { 
     return 'team'; 
    } 

    public function getDefaultOptions(array $options) 
    { 
     return array('data_class' => 'Tennisconnect\DashboardBundle\Entity\Team'); 
    } 
} 

ChallengeType:

<?php 

namespace Tennisconnect\DashboardBundle\Form\Type; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilder; 

class ChallengeType extends AbstractType 
{ 
    public function buildForm(FormBuilder $builder, array $options) 
    { 
     $builder 
      ->add('teams', 'collection', array(
       'type' => new TeamType(), 
       'allow_add' => true 
      )) 
      ->add('place') 
      ->add('date'); 
    } 

    public function getName() 
    { 
     return 'challenge'; 
    } 

    public function getDefaultOptions(array $options) 
    { 
     return array('data_class' => 'Tennisconnect\DashboardBundle\Entity\Challenge'); 
    } 
} 

回答

1

刪除用戶相關的領域,並添加兩個未綁定字段您TeamType,如。

$builder->add('new_member_1', 'text', array('property_path' => false)) 
     ->add('new_member_2', 'text', array('property_path' => false)); 

這將在您的渲染表單中顯示兩個文本字段。然後在控制器中寫入一些讀取這些字段的邏輯,提取用戶並將其添加到您的團隊中。

// ... controller action 
// first bind request 
$form->bindRequest($request); 
if ($form->isValid()) { 
    // fetch first username 
    $username = $form->get('new_member_1')->getData(); 
    $user = $this->getDoctrine()->getRepository('YourBundle:User')->findOneByUsername($username); 
    $team->addUser($user); 
    // same for second user 
} 

這是一個簡約的例子。所以你需要添加一些驗證,錯誤處理等,但它顯示它可能爲你工作。

編輯:

如果您有嵌套表格類型,你可以通過通過元素走路越來越下降的路徑你的孩子。

$form->get('outer_type')->get('team_type')->get('new_member_1')->getData(); 
+0

THX的答案:)這就是我一直在尋找。但是,如果團隊形式嵌入另一種形式,我將如何從控制器中的文本字段獲取數據? – mattyh88

+0

看到latetes編輯:) – hacksteak25

+0

我有現在這樣:$ USERNAME = $形式 - >獲取( '團隊') - >獲取( 'player_one') - >的getData();我應該放什麼而不是'outer_type'?我認爲挑戰實體中的財產?或者說TeamType?這兩個選項都給我一個錯誤。 – mattyh88

1

這是我拿來從收集數據:

foreach($form->get('teams') as $team_form) 
{ 
    $player_one = $team_form->get('player_one')->getData(); 
    $player_two = $team_form->get('player_two')->getData(); 
} 
+0

該死的,它是可迭代的xD感謝您的反饋 – hacksteak25

相關問題