How do you pass the parent entity to a form in Symfony?











up vote
0
down vote

favorite












Suppose I have two entities: a post and a comment. Each post can have many comments. Now, suppose I have a comment form. It is supposed to take user input and store it in the database.



Simple stuff. At least, it should be, but I can't get it to work.



How do I refer to the post (parent) when creating the comment (child)? I tried manually passing the post_id to the comment form as a hidden field, but received an error complaining about how the post ID is a string.



Expected argument of type "AppEntityPost or null", "string" given.




Here is my code so far. Can someone nudge me into the right direction?



CommentType.php



public function buildForm(FormBuilderInterface $builder, array $options)
{
$post_id = $options['post_id'];

$builder->add('content', TextareaType::class, [
'constraints' => [
new AssertNotBlank(['message' => 'Your comment cannot be blank.']),
new AssertLength([
'min' => 10,
'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
]),
],
])->add('post', HiddenType::class, ['data' => $post_id]);
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comment::class,
'post_id' => NULL,
]);
}




PostController.php (this is where the comment form appears)



// Generate the comment form.
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment, [
'action' => $this->generateUrl('new_comment'),
'post_id' => $post_id,
]);




CommentController.php



/**
* @param Request $request
* @Route("/comment/new", name="new_comment")
* @return
*/
public function new(Request $request, UserInterface $user)
{
// 1) Build the form
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);

// 2) Handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
// 3) Save the comment!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
}

return $this->redirectToRoute('homepage');
}




Thank you very much for your help!










share|improve this question


















  • 1




    As mentioned in error message you need to pass the entity object of your post_id.
    – Ben
    Nov 4 at 23:39















up vote
0
down vote

favorite












Suppose I have two entities: a post and a comment. Each post can have many comments. Now, suppose I have a comment form. It is supposed to take user input and store it in the database.



Simple stuff. At least, it should be, but I can't get it to work.



How do I refer to the post (parent) when creating the comment (child)? I tried manually passing the post_id to the comment form as a hidden field, but received an error complaining about how the post ID is a string.



Expected argument of type "AppEntityPost or null", "string" given.




Here is my code so far. Can someone nudge me into the right direction?



CommentType.php



public function buildForm(FormBuilderInterface $builder, array $options)
{
$post_id = $options['post_id'];

$builder->add('content', TextareaType::class, [
'constraints' => [
new AssertNotBlank(['message' => 'Your comment cannot be blank.']),
new AssertLength([
'min' => 10,
'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
]),
],
])->add('post', HiddenType::class, ['data' => $post_id]);
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comment::class,
'post_id' => NULL,
]);
}




PostController.php (this is where the comment form appears)



// Generate the comment form.
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment, [
'action' => $this->generateUrl('new_comment'),
'post_id' => $post_id,
]);




CommentController.php



/**
* @param Request $request
* @Route("/comment/new", name="new_comment")
* @return
*/
public function new(Request $request, UserInterface $user)
{
// 1) Build the form
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);

// 2) Handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
// 3) Save the comment!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
}

return $this->redirectToRoute('homepage');
}




Thank you very much for your help!










share|improve this question


















  • 1




    As mentioned in error message you need to pass the entity object of your post_id.
    – Ben
    Nov 4 at 23:39













up vote
0
down vote

favorite









up vote
0
down vote

favorite











Suppose I have two entities: a post and a comment. Each post can have many comments. Now, suppose I have a comment form. It is supposed to take user input and store it in the database.



Simple stuff. At least, it should be, but I can't get it to work.



How do I refer to the post (parent) when creating the comment (child)? I tried manually passing the post_id to the comment form as a hidden field, but received an error complaining about how the post ID is a string.



Expected argument of type "AppEntityPost or null", "string" given.




Here is my code so far. Can someone nudge me into the right direction?



CommentType.php



public function buildForm(FormBuilderInterface $builder, array $options)
{
$post_id = $options['post_id'];

$builder->add('content', TextareaType::class, [
'constraints' => [
new AssertNotBlank(['message' => 'Your comment cannot be blank.']),
new AssertLength([
'min' => 10,
'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
]),
],
])->add('post', HiddenType::class, ['data' => $post_id]);
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comment::class,
'post_id' => NULL,
]);
}




PostController.php (this is where the comment form appears)



// Generate the comment form.
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment, [
'action' => $this->generateUrl('new_comment'),
'post_id' => $post_id,
]);




CommentController.php



/**
* @param Request $request
* @Route("/comment/new", name="new_comment")
* @return
*/
public function new(Request $request, UserInterface $user)
{
// 1) Build the form
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);

// 2) Handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
// 3) Save the comment!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
}

return $this->redirectToRoute('homepage');
}




Thank you very much for your help!










share|improve this question













Suppose I have two entities: a post and a comment. Each post can have many comments. Now, suppose I have a comment form. It is supposed to take user input and store it in the database.



Simple stuff. At least, it should be, but I can't get it to work.



How do I refer to the post (parent) when creating the comment (child)? I tried manually passing the post_id to the comment form as a hidden field, but received an error complaining about how the post ID is a string.



Expected argument of type "AppEntityPost or null", "string" given.




Here is my code so far. Can someone nudge me into the right direction?



CommentType.php



public function buildForm(FormBuilderInterface $builder, array $options)
{
$post_id = $options['post_id'];

$builder->add('content', TextareaType::class, [
'constraints' => [
new AssertNotBlank(['message' => 'Your comment cannot be blank.']),
new AssertLength([
'min' => 10,
'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
]),
],
])->add('post', HiddenType::class, ['data' => $post_id]);
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comment::class,
'post_id' => NULL,
]);
}




PostController.php (this is where the comment form appears)



// Generate the comment form.
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment, [
'action' => $this->generateUrl('new_comment'),
'post_id' => $post_id,
]);




CommentController.php



/**
* @param Request $request
* @Route("/comment/new", name="new_comment")
* @return
*/
public function new(Request $request, UserInterface $user)
{
// 1) Build the form
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);

// 2) Handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
// 3) Save the comment!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
}

return $this->redirectToRoute('homepage');
}




Thank you very much for your help!







php symfony symfony4






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 4 at 23:30









Nathanael

2,88242238




2,88242238








  • 1




    As mentioned in error message you need to pass the entity object of your post_id.
    – Ben
    Nov 4 at 23:39














  • 1




    As mentioned in error message you need to pass the entity object of your post_id.
    – Ben
    Nov 4 at 23:39








1




1




As mentioned in error message you need to pass the entity object of your post_id.
– Ben
Nov 4 at 23:39




As mentioned in error message you need to pass the entity object of your post_id.
– Ben
Nov 4 at 23:39












1 Answer
1






active

oldest

votes

















up vote
2
down vote













You just need to pass the actual Post entity, not just the id. Try this:



CommentController.php



public function new(Request $request, UserInterface $user, PostInterface $post)
{
// 1) Build the form
$comment = new Comment();
$comment->setPost($post); //where $post is instance of AppEntityPost
$form = $this->createForm(CommentType::class, $comment);

// 2) Handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
// 3) Save the comment!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
}

return $this->redirectToRoute('homepage');
}


CommentType



public function buildForm(FormBuilderInterface $builder, array $options)
{
//don't need to set the $post here

$builder->add('content', TextareaType::class, [
'constraints' => [
new AssertNotBlank(['message' => 'Your comment cannot be blank.']),
new AssertLength([
'min' => 10,
'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
]),
],
])->add('post', HiddenType::class, ['data' => $post_id]);
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comment::class
//don't need the default here either
]);
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53146528%2fhow-do-you-pass-the-parent-entity-to-a-form-in-symfony%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote













    You just need to pass the actual Post entity, not just the id. Try this:



    CommentController.php



    public function new(Request $request, UserInterface $user, PostInterface $post)
    {
    // 1) Build the form
    $comment = new Comment();
    $comment->setPost($post); //where $post is instance of AppEntityPost
    $form = $this->createForm(CommentType::class, $comment);

    // 2) Handle the submit (will only happen on POST)
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid())
    {
    // 3) Save the comment!
    $entityManager = $this->getDoctrine()->getManager();
    $entityManager->persist($comment);
    $entityManager->flush();
    }

    return $this->redirectToRoute('homepage');
    }


    CommentType



    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    //don't need to set the $post here

    $builder->add('content', TextareaType::class, [
    'constraints' => [
    new AssertNotBlank(['message' => 'Your comment cannot be blank.']),
    new AssertLength([
    'min' => 10,
    'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
    ]),
    ],
    ])->add('post', HiddenType::class, ['data' => $post_id]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
    $resolver->setDefaults([
    'data_class' => Comment::class
    //don't need the default here either
    ]);
    }





    share|improve this answer



























      up vote
      2
      down vote













      You just need to pass the actual Post entity, not just the id. Try this:



      CommentController.php



      public function new(Request $request, UserInterface $user, PostInterface $post)
      {
      // 1) Build the form
      $comment = new Comment();
      $comment->setPost($post); //where $post is instance of AppEntityPost
      $form = $this->createForm(CommentType::class, $comment);

      // 2) Handle the submit (will only happen on POST)
      $form->handleRequest($request);
      if ($form->isSubmitted() && $form->isValid())
      {
      // 3) Save the comment!
      $entityManager = $this->getDoctrine()->getManager();
      $entityManager->persist($comment);
      $entityManager->flush();
      }

      return $this->redirectToRoute('homepage');
      }


      CommentType



      public function buildForm(FormBuilderInterface $builder, array $options)
      {
      //don't need to set the $post here

      $builder->add('content', TextareaType::class, [
      'constraints' => [
      new AssertNotBlank(['message' => 'Your comment cannot be blank.']),
      new AssertLength([
      'min' => 10,
      'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
      ]),
      ],
      ])->add('post', HiddenType::class, ['data' => $post_id]);
      }

      public function configureOptions(OptionsResolver $resolver)
      {
      $resolver->setDefaults([
      'data_class' => Comment::class
      //don't need the default here either
      ]);
      }





      share|improve this answer

























        up vote
        2
        down vote










        up vote
        2
        down vote









        You just need to pass the actual Post entity, not just the id. Try this:



        CommentController.php



        public function new(Request $request, UserInterface $user, PostInterface $post)
        {
        // 1) Build the form
        $comment = new Comment();
        $comment->setPost($post); //where $post is instance of AppEntityPost
        $form = $this->createForm(CommentType::class, $comment);

        // 2) Handle the submit (will only happen on POST)
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid())
        {
        // 3) Save the comment!
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($comment);
        $entityManager->flush();
        }

        return $this->redirectToRoute('homepage');
        }


        CommentType



        public function buildForm(FormBuilderInterface $builder, array $options)
        {
        //don't need to set the $post here

        $builder->add('content', TextareaType::class, [
        'constraints' => [
        new AssertNotBlank(['message' => 'Your comment cannot be blank.']),
        new AssertLength([
        'min' => 10,
        'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
        ]),
        ],
        ])->add('post', HiddenType::class, ['data' => $post_id]);
        }

        public function configureOptions(OptionsResolver $resolver)
        {
        $resolver->setDefaults([
        'data_class' => Comment::class
        //don't need the default here either
        ]);
        }





        share|improve this answer














        You just need to pass the actual Post entity, not just the id. Try this:



        CommentController.php



        public function new(Request $request, UserInterface $user, PostInterface $post)
        {
        // 1) Build the form
        $comment = new Comment();
        $comment->setPost($post); //where $post is instance of AppEntityPost
        $form = $this->createForm(CommentType::class, $comment);

        // 2) Handle the submit (will only happen on POST)
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid())
        {
        // 3) Save the comment!
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($comment);
        $entityManager->flush();
        }

        return $this->redirectToRoute('homepage');
        }


        CommentType



        public function buildForm(FormBuilderInterface $builder, array $options)
        {
        //don't need to set the $post here

        $builder->add('content', TextareaType::class, [
        'constraints' => [
        new AssertNotBlank(['message' => 'Your comment cannot be blank.']),
        new AssertLength([
        'min' => 10,
        'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
        ]),
        ],
        ])->add('post', HiddenType::class, ['data' => $post_id]);
        }

        public function configureOptions(OptionsResolver $resolver)
        {
        $resolver->setDefaults([
        'data_class' => Comment::class
        //don't need the default here either
        ]);
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 5 at 3:39

























        answered Nov 5 at 3:33









        flint

        142113




        142113






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53146528%2fhow-do-you-pass-the-parent-entity-to-a-form-in-symfony%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()