TYPO3:如何跳过关联子对象未在表单中出现的属性验证?
嘿,我懂你现在的困扰啦——在新增Document的表单里只用到了User的部分属性,想跳过User模型里那些没出现在表单里的字段验证,对吧?你已经知道怎么处理主对象Document的属性跳过了,子对象User的处理其实思路一致,只是需要先拿到关联User的属性映射配置就行,我给你具体说说怎么做:
核心思路
你需要先获取Document的属性映射配置,然后定位到关联的User字段(比如你实体里定义的多对多关联字段名,比如user或者users),再针对这个子对象配置跳过不需要验证的属性。
具体代码示例
假设你的Document实体里,多对多关联User的字段名为user(如果是多用户集合就是users,根据你的实际代码调整),可以这样写:
// 先获取Document的属性映射配置(和你原来的写法一致) $docMappingConfig = $this->arguments->getArgument('document')->getPropertyMappingConfiguration(); // 获取关联User字段的子配置 $userMappingConfig = $docMappingConfig->getConfigurationFor('user'); // 跳过User模型中未在表单里出现的属性,比如'email'、'password'、'createdAt'等 $userMappingConfig->skipProperties('email', 'password', 'createdAt');
完整场景示例(比如在控制器处理表单时)
如果是在表单提交后的验证环节处理,代码大概是这样:
public function createDocument(Request $request) { $document = new Document(); $form = $this->createForm(DocumentType::class, $document); $form->handleRequest($request); if ($form->isSubmitted()) { // 在验证前,先配置跳过User的多余属性 $docMappingConfig = $this->arguments->getArgument('document')->getPropertyMappingConfiguration(); $userMappingConfig = $docMappingConfig->getConfigurationFor('user'); // 替换成你实际要跳过的User属性 $userMappingConfig->skipProperties('username', 'lastLogin'); if ($form->isValid()) { // 保存到数据库 $em = $this->getDoctrine()->getManager(); $em->persist($document); $em->flush(); return $this->redirectToRoute('document_index'); } } return $this->render('document/new.html.twig', [ 'form' => $form->createView(), ]); }
注意事项
- 关联字段名要准确:必须和你Document实体中定义的多对多关联字段名称完全一致,比如如果实体里是
private $users;,那代码里就要用getConfigurationFor('users')。 - 多对多集合的情况:如果你的关联是多个User的集合,
getConfigurationFor('users')会自动应用到集合里的每一个User对象上,不需要单独遍历处理。 - 确认依赖配置:你用到的
getPropertyMappingConfiguration()方法一般来自FOSRestBundle,要确保你的项目已经正确安装并配置了这个Bundle。
内容的提问来源于stack exchange,提问作者andreas
相关产品推荐
相关产品推荐

