Php 从EntityType Symfony获取值
我无法从EntityType获取值。我有最新版本3.3.6Php 从EntityType Symfony获取值,php,html,symfony,frameworks,Php,Html,Symfony,Frameworks,我无法从EntityType获取值。我有最新版本3.3.6 class BuildType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('title', TextType::class) ->add('save', SubmitType::class
class BuildType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array
$options)
{
$builder
->add('title', TextType::class)
->add('save', SubmitType::class, array('label' => 'Create Post'))
->add('team', CollectionType::class, array(
// each entry in the array will be an "email" field
'entry_type' => TeamType::class,
// these options are passed to each "email" type
'entry_options' => array(
'attr' => array('class' => 'form-control'),
),
'label' => false,
'allow_add' => true,
'prototype' => true,
'mapped' => false
));
}
}
我尝试了所有方法,但无法接受TeamType的“name”值。提交表格后,我会
foreach ($form["team"]->getData() as $value) {
'name' => $value['name']
但该值为空。如果我尝试转储请求,并且该值存在。我可以获取其他值并保存在数据库中。只有EntityType我不能。
有人知道怎么做吗?我想你使用的是
多通关系
使用AJAX
如果您试图在提交后获取数据,可以先在视图中执行此操作:
$('#elementWhereYouAreTEAMType').find('input').each(function (i,v) {
var valTeam = $(this).val(); //take value
// adding data, create an associative array.
formData.append("team["+ i +"]", valTeam);
});
必须将formData
与data
类似的参数放入ajax JQuery
现在,服务器端:
public function createTeamNow(Request $request) {// ajax
$teams = $request->request->get('team'); // getting array
if(!is_null($teams)) {// if user added team
foreach ($teams as $team) {
// dump($team);
//create an instance for each element, it does not replace a data with the above
$teamType = new TeamType();
$teamName->setName($team);
$this->em->persist($teamType);
}
}
}
没有AJAX
/**
* @Route("/slim/1" , name="data_x")
*/
public function slimExampleAction(Request $request)
{
$form = $this->createForm(TeamType::class);
$form->handleRequest($request);
if ($form->isSubmitted() /*&& $form->isValid()*/) {
// When you've ManyToOne relationship, that field returns ArrayCollection class, it has several method to get data on differents ways, iterate with it, for example toArray is one
$data = $form->getData();
dump($data->getDescription()->toArray());die;
}
return $this->render('AppBundle:view.html.twig', array(
'form' => $form->createView(),
));
}
EntityType作为对象返回。您应该使用模型getter函数
$form->get('name')->getData()->getId(); // getName() vs..
这里有一个类似的例子
您试图在哪里访问$form['team']
?您能提供一个代码片段吗?奇怪的是,如果TeamType
只包含一个字段,为什么要将其提取到单独的表单类型中?
$form->get('name')->getData()->getId(); // getName() vs..