草庐IT

php - Symfony 一对多不链接父级

coder 2024-04-07 原文

我有一个包含 3 个实体的测验结构:

  • 测验有问题(OneToMany)
  • 问题有测验(多对一)
  • 问题有答案(一对多)
  • 答案有问题(多对一)

代码如下所示:

测验实体

class Quiz
{    
    /**
     * @ORM\OneToMany(targetEntity="Question", mappedBy="quiz", cascade={"persist", "remove"})
     */
    private $questions;

    public function __construct() {
        $this->questions = new ArrayCollection();
    }

    public function addQuestion(\Cariboo\QuizBundle\Entity\Question $questions)
    {
        $questions->setQuiz( $this );
        // die(); Not dying here...
        $this->questions[] = $questions;

        return $this;
    }

    public function removeQuestion(\Cariboo\QuizBundle\Entity\Question $questions)
    {
        $this->questions->removeElement($questions);
    }

    public function getQuestions()
    {
        return $this->questions;
    }
}

问题实体

class Question
{
    /**
     * @ORM\OneToMany(targetEntity="Answer", mappedBy="question", cascade={"persist", "remove"})
     */
    private $answers;

    /**
     * @ORM\ManyToOne(targetEntity="Cariboo\QuizBundle\Entity\Quiz", cascade={"persist"})
     */
    private $quiz;

    public function addAnswer(\Cariboo\QuizBundle\Entity\Answer $answers)
    {
        $answers->setQuestion( $this );
        $this->answers[] = $answers;

        return $this;
    }

    public function removeAnswer(\Cariboo\QuizBundle\Entity\Answer $answers)
    {
        $this->answers->removeElement($answers);
    }

    public function getAnswers()
    {
        return $this->answers;
    }

    public function setQuiz(\Cariboo\QuizBundle\Entity\Quiz $quiz = null)
    {
        $this->quiz = $quiz;

        return $this;
    }

    public function getQuiz()
    {
        return $this->quiz;
    }
}

答案实体

class Answer
{
    /**
     * @ORM\ManyToOne(targetEntity="Cariboo\QuizBundle\Entity\Question")
     */
    private $question;

    public function setQuestion(\Cariboo\QuizBundle\Entity\Question $question = null)
    {
        $this->question = $question;

        return $this;
    }

    public function getQuestion()
    {
        return $this->question;
    }
}

我级联持久化它们。

我按照 Cascaded persist not working (Doctrine ORM + Symfony 2) 中的说明配置了我的 setter

addAnswer 被执行,对于答案,问题设置正确。但是 addQuestion 没有设置测验。

image of what gets dumped upon sending the form

我可以在我的 Controller 中添加一个 foreach 但我对此并不满意,因为我觉得我没有利用 symfony 的力量。 (Entity doesn't associate correctly 没有重复)

    if ( $form->isValid() ) {
        foreach ( $quiz->getQuestions() as $question ) {
            $question->setQuiz( $quiz );
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist( $quiz );
        $em->flush();

        return $this->redirect( $this->generateUrl( 'quiz_show', array(
            'slug' => $quiz->getSlug()
        ) ) );
    }

我不明白为什么 addQuestion 没有被执行。

编辑

我的测验表单

    $builder
        ->add( 'questions', 'collection', array(
            'type' => new QuestionType(),
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
            'prototype_name' => '__qst_prot__'
        ) )
    ;

问题的部分构建器

    $builder
        ->add( 'question', 'text' )
        ->add( 'answers', 'collection', array(
            'type' => new AnswerType(),
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
            'prototype_name' => '__asw_prot__'
        ) );

我的答案表

$builder
        ->add( 'answer', 'text' )
        ->add( 'correct' )
    ;

最佳答案

问题出在 collection 表单类型中。如果要调用父实体 setter ,则需要将 by_reference 设置为 false

Symfony 文档:

类似地,如果您使用 CollectionType 字段,其中您的基础集合数据是一个对象(就像 Doctrine 的 ArrayCollection),那么如果您需要加法器和移除器(例如 addAuthor()和 removeAuthor()) 被调用。

在这里阅读更多:http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference

关于php - Symfony 一对多不链接父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35624430/

有关php - Symfony 一对多不链接父级的更多相关文章

  1. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  2. ruby-on-rails - Prawn - 表格单元格内的链接 - 2

    我正在尝试用Prawn生成PDF。在我的PDF模板中,我有带单元格的表格。在其中一个单元格中,我有一个电子邮件地址:cell_email=pdf.make_cell(:content=>booking.user_email,:border_width=>0)我想让电子邮件链接到“mailto”链接。我知道我可以这样链接:pdf.formatted_text([{:text=>booking.user_email,:link=>"mailto:#{booking.user_email}"}])但是将这两行组合起来(将格式化文本作为内容)不起作用:cell_email=pdf.make_c

  3. ruby - 使用 Watir 检查错误链接 - 2

    我有一个未排序的链接列表,我将其保存在旁边,我想单击每个链接并确保它转到真实页面而不是404、500等。问题是我不知道该怎么做。是否有一些我可以检查的对象会给我http状态代码或任何东西?mylinks=Browser.ul(:id,'my_ul_id').linksmylinks.eachdo|link|link.click#needtocheckfora200statusorsomethinghere!how?Browser.backend 最佳答案 我的回答与铁皮人的想法类似。require'net/http'require'

  4. ruby - 如何为 pbcopy 生成富文本链接 - 2

    我一直在玩一个脚本,它在Chrome中获取选定的文本并在Google中查找它,提供四个最佳选择,然后粘贴相关链接。它以不同的格式粘贴,具体取决于当前在Chrome中打开的页面-DokuWiki打开的DokuWiki格式,普通网站的HTML,我想要我的WordPress所见即所得编辑器的富文本。我尝试使用pbpaste-Preferrtf来查看没有其他样式的富文本链接在粘贴板上的样子,但它仍然输出纯文本。在文本编辑中保存文件并进行试验后,我想出了以下内容text=%q|{\rtf1{\field{\*\fldinst{HYPERLINK"URL"}}{\fldrsltTEXT}}}|te

  5. ruby-on-rails - 如何从按钮或链接单击的 View 调用 Rails 方法 - 2

    基本上,我试图在用户单击链接(或按钮或某种类型的交互元素)时执行Rails方法。我试着把它放在View中:但这似乎没有用。它最终只是在用户甚至没有点击“添加”链接的情况下调用该函数。我也用link_to试过了,但也没用。我开始认为没有一种干净的方法可以做到这一点。无论如何,感谢您的帮助。附言。我在ApplicationController中定义了该方法,它是一个辅助方法。 最佳答案 View和Controller是相互独立的。为了使链接在Controller内执行函数调用,您需要对应用程序中的端点执行ajax调用。该路由应调用rub

  6. ruby - 在 Mechanize 中使用 JavaScript 单击链接 - 2

    我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan

  7. ruby - 使用指向 ruby​​ 可执行文件的符号链接(symbolic link)时查找相关库 - 2

    假设您有一个可执行文件foo.rb,其库bar.rb的布局如下:/bin/foo.rb/lib/bar.rb在foo.rb的header中放置以下要求以在bar.rb中引入功能:requireFile.dirname(__FILE__)+"../lib/bar.rb"只要对foo.rb的所有调用都是直接的,这就可以正常工作。如果你把$HOME/project和符号链接(symboliclink)foo.rb放入$HOME/usr/bin,然后__FILE__解析为$HOME/usr/bin/foo.rb,因此无法找到bar.rb关于foo.rb的目录名.我意识到像ruby​​gems这

  8. ruby-on-rails -/usr/local/lib/libz.1.dylib,文件是为 i386 构建的,它不是被链接的体系结构 (x86_64) - 2

    在我的mac上安装几个东西时遇到这个问题,我认为这个问题来自将我的豹子升级到雪豹。我认为这个问题也与macports有关。/usr/local/lib/libz.1.dylib,filewasbuiltfori386whichisnotthearchitecturebeinglinked(x86_64)有什么想法吗?更新更具体地说,这发生在安装nokogirigem时日志看起来像:xslt_stylesheet.c:127:warning:passingargument1of‘Nokogiri_wrap_xml_document’withdifferentwidthduetoproto

  9. ruby - 使用 Nokogiri 和 Ruby 从 html 文档获取链接和 href 文本? - 2

    我正在尝试使用nokogirigem提取页面上的所有url及其链接文本,并将链接文本和url存储在散列中。FooBar我想回去{"Foo"=>"#foo","Bar"=>"#bar"} 最佳答案 这是一个单行:Hash[doc.xpath('//a[@href]').map{|link|[link.text.strip,link["href"]]}]#=>{"Foo"=>"#foo","Bar"=>"#bar"}拆分一点可以说更具可读性:h={}doc.xpath('//a[@href]').eachdo|link|h[link.t

  10. ruby-on-rails - 如何将 aria-label 属性添加到 View 中的链接? - 2

    我正在尝试将aria-label属性添加到链接以使其更易于访问。当我这样做时,它按预期工作:"aria-label="">VersionPostman但这不是:我收到“意外的tLABEL”语法错误。任何人都知道这是什么问题?谢谢。 最佳答案 问题出在标签上的破折号上。试试这个:get_aria_label_current_page('home')%>更新现在在ruby​​2.2中你可以:'aria-label':get_aria_label_current_page('home') 关于

随机推荐