簡體   English   中英

Symfony 2 - 定義 EntityType 的選定值

[英]Symfony 2 - Define selected value for EntityType

我從事 Symfony 2.8 項目。 該系統使用 TextType / DateTimeType / MoneyType 但也不適用於 EntityType 和 DateType。

我嘗試從 session 中的值定義我的 EntityType 的默認值,當我在 Controller 中創建表單時傳入參數,如下所示:

$filter_form = $this->createForm(FilterActeType::class, null, [
        'filters' => array_merge(
            $defaultFilter,
            $paginatorService->getFiltersFromSessionByContext($usr->getId(), $request->attributes->get('_route'))
        )
    ]);

我嘗試在 EntityType 中使用datachoice_value參數,但問題是一樣的:當我重新加載頁面時,表單過濾器中不存在數據,而數據位於變量 session 中。

數據參數無匿名 function 的情況:

$builder->add('etude', EntityType::class, [
            'label' => $this->translator->trans('Étude'),
            'class' => Etude::class,
            'required'  => false,
            'attr' => array('dyn-form-data' => 'cabinet,createur,destinataire'), // Champs dynamique => on renseigne le ou les enfants (le(s) champ(s) qui doit être mise à jour à la modification de celui-ci)
            'data' => $this->getDataFromFilters($options, 'etude'),
        ]);

觀察:這個案例已經返回了一個錯誤信息:“...傳遞給選擇字段必須被管理。也許你忘記將它持久化在實體管理器中?”。

帶有匿名 function 的數據參數的情況:

$builder->add('etude', EntityType::class, [
            'label' => $this->translator->trans('Étude'),
            'class' => Etude::class,
            'required'  => false,
            'attr' => array('dyn-form-data' => 'cabinet,createur,destinataire'), // Champs dynamique => on renseigne le ou les enfants (le(s) champ(s) qui doit être mise à jour à la modification de celui-ci)
            'data' => function (EntityRepository $er) use ($options) {
                if (null != $etude = $this->getDataFromFilters($options, 'etude')) {
                    $er->createQueryBuilder('e')->andWhere('e.id = :id')->setParameter('id', $etude->getId());
                }
            }
        ]);

Observations:: 沒有錯誤返回,但也沒有數據。

帶有choice_value 參數的情況:

$builder->add('etude', EntityType::class, [
            'label' => $this->translator->trans('Étude'),
            'class' => Etude::class,
            'required'  => false,
            'attr' => array('dyn-form-data' => 'cabinet,createur,destinataire'), // Champs dynamique => on renseigne le ou les enfants (le(s) champ(s) qui doit être mise à jour à la modification de celui-ci)
            'choice_value' => function() use ($options) {
                return $this->getDataFromFilters($options, 'etude');
            },
        ]);

觀察結果:沒有錯誤返回,也沒有數據。

來自表格 object 的 getDataFromFilters 方法的代碼:

/**
 * @param array $filters
 * @param string $field
 *
 * @return \DateTime|Etude|Cabinet|string|int|float|TypeDocument|ModeDistribution|null
 */
private function getDataFromFilters(array $options, string $field)
{
    return (isset($options['filters'][$field]) && (null != $value = $options['filters'][$field])) ? $value : null;
}

編輯(2021 年 11 月 24 日):添加了調試

這是存儲在 session 中的實體的調試:

etude: Etude {#812 ▼
+__isInitialized__: true
-id: 1
-libelle: "Toto"
-mail: "yolo.toto@toto-france.fr"
-origines: PersistentCollection {#811 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#810 ▼
    -elements: []
  }
  #initialized: false
}
-utilisateurs: PersistentCollection {#809 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#808 ▼
    -elements: []
  }
  #initialized: false
}
-cabinets: PersistentCollection {#807 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#806 ▼
    -elements: array:1 [▼
      0 => Cabinet {#805 ▼
        -id: 1
        -libelle: "Cabinet Toto"
        -etude: Etude {#812 …2}
        -infoUserByEtude: PersistentCollection {#804 ▼
          -snapshot: []
          -owner: null
          -association: null
          -em: null
          -backRefFieldName: null
          -typeClass: null
          -isDirty: false
          #collection: ArrayCollection {#803 ▼
            -elements: []
          }
          #initialized: false
        }
        -adresse: null
        -villeCP: null
      }
    ]
  }
  #initialized: true
}
-actes: PersistentCollection {#802 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#801 ▼
    -elements: []
  }
  #initialized: false
}
-typeDocuments: PersistentCollection {#800 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#799 ▼
    -elements: []
  }
  #initialized: false
}
-modeDistributions: PersistentCollection {#798 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#797 ▼
    -elements: []
  }
  #initialized: false
}
-themeMainColor: null
-themeAccentColor: null
-logo: null
-background: null
-sous_domaine: "yolo"
-transactions: PersistentCollection {#794 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#795 ▼
    -elements: []
  }
  #initialized: false
}
-templates: PersistentCollection {#796 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#138 ▼
    -elements: []
  }
  #initialized: false
}
-aliasMail: "contact@toto-france.fr"
-smsActif: false
-notificationSmsActif: false
-paiementActif: true
-blocNoteActif: false
-connexionDirecteActif: false
-dureeTokenConnexionDirecte: 2
-smsSenderName: null
-locale: null
-faxActif: false
-dossierDebiteurActif: true
-defaultModuleActif: true
-frequenceNotification: "day"
-objetMail: null
-lienRgpd1: null
-lienRgpd2: null
-mailEchecNotification: null
 …2

}

使用 Symfony/PHP:

看看這個答案,希望它適用於您正在使用的版本,我相信是因為它說它是在 2.7 版本上添加的: https://stackoverflow.com/a/35941528/17089665

使用 JS:

您可以發送一個變量,即使它存儲在當前的 session 中,但您應該在controller中進行。 創建form時,可以在渲染 function 中發送變量。

通常,您將發送一個 object 作為參數,該 object 是您正在制作表單的 class。 我建議您將Entity的設置器用於預定義值。

所以......一個簡單的例子,如果你想顯示一個下拉列表:

AppleController 用於創建一盒蘋果:

$arrayOfTypes = however_you_get_your_info(); // <- With different types of apples
$newAppleBox = new AppleBox();
$newAppleBox->setWhateverVariableWithPredefinedValue() // Here, for example, if you were to create a modifyUserInfo template or something like this, you could prepopulate this with the current info so they don't need to write everything again.
$form = $this->createForm(AppleRegistrationType::class, $newAppleBox);

if ($form->isSubmitted() && $form->isValid()) {
// blablabla
}

return $this->render('registrations/appleBox.html.twig', [
        'appleBoxRegistrationForm' => $form->createView(),
        'typesArray' => $arrayOfTypes
]);

然后,在您的表單中,您通常創建EntityType

use App\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...

$builder->add('users', EntityType::class, [
    'class' => User::class,
     blablabla
]);

最后,在您的模板中,您可以使用twigjs動態檢索該列表並將其放入新的<select>中(我相信EntityType在 HTML 中被引用)。

另外,看看官方文檔:

https://symfony.com/doc/current/reference/forms/types/entity.html#using-choices

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM