Данные публикации содержат атрибут списка в symfony - PullRequest
1 голос
/ 19 января 2020

У меня много связей между Tweet и Hashtag. Я пытаюсь отправить форму Tweet, чтобы создать твит с выбранными хэштегами из флажков. Кроме того, я использую FosRestBundle.

Есть ли какое-нибудь решение?

Я пытался сделать так, но данные вставлены, но хэштеги никогда не были!

Tweet Entity:

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\TweetRepository")
 */
 class Tweet
 {
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="date")
 */
private $PublishDate;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Hashtag", inversedBy="tweets")
 */
private $hashtags;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\TwitterProfile", inversedBy="tweets")
 */
private $author;

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

public function getId(): ?int
{
    return $this->id;
}

public function getPublishDate(): ?\DateTimeInterface
{
    return $this->PublishDate;
}

public function setPublishDate(\DateTimeInterface $PublishDate): self
{
    $this->PublishDate = $PublishDate;

    return $this;
}

/**
 * @return Collection|Hashtag[]
 */
public function getHashtags(): Collection
{
    return $this->hashtags;
}

public function addHashtag(Hashtag $hashtag): self
{
    if (!$this->hashtags->contains($hashtag)) {
        $this->hashtags[] = $hashtag;
    }

    return $this;
}

public function removeHashtag(Hashtag $hashtag): self
{
    if ($this->hashtags->contains($hashtag)) {
        $this->hashtags->removeElement($hashtag);
    }

    return $this;
}

public function getAuthor(): ?TwitterProfile
{
    return $this->author;
}

public function setAuthor(?TwitterProfile $author): self
{
    $this->author = $author;

    return $this;
}
}

TweetType:

   <?php


    namespace App\Forms;

    use App\Entity\Tweet;
    use App\Entity\TwitterProfile;
    use Doctrine\ORM\EntityRepository;
    use Symfony\Bridge\Doctrine\Form\Type\EntityType;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\Extension\Core\Type\CollectionType;
    use Symfony\Component\Form\Extension\Core\Type\DateType;
    use Symfony\Component\Form\Extension\Core\Type\SubmitType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;

    class TweetType extends AbstractType
    {
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
      $builder
        ->add('PublishDate', DateType::class,[
            'widget' => 'choice'
        ])

        ->add('hashtags', CollectionType::class,[
            'entry_type' => HashtagType::class
        ])

        ->add('author', EntityType::class,[
            'class' => TwitterProfile::class,
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('tp');
            }
        ])
        ->add('save', SubmitType::class)
    ;

}
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class'
        =>
            Tweet::class,
        'csrf_protection'
        =>
            false
    ));
}
}

TweetController:

<?php

  namespace App\Controller;

  use App\Entity\Tweet;
  use App\Forms\TweetType;
  use Doctrine\Common\Collections\ArrayCollection;
  use FOS\RestBundle\Controller\FOSRestController;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\HttpFoundation\Response;
  use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  use Symfony\Component\Routing\Annotation\Route;
  use FOS\RestBundle\Controller\Annotations as Rest;

  class TweetController extends FOSRestController
 {

 /**
 * List All Tweets
 * @Rest\Get("/getAllTweets")
 * @return Response
 */
public function getTweets()
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $tweets=$repository->findall();
    return$this->handleView($this->view($tweets));
}

/**
 * List One Tweet
 * @Rest\Get("/tweet/{id}")
 * @param int $id
 * @return Response
 */
public function getOneTweet(int $id)
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $tweet=$repository->find($id);

    if ($tweet == null){
        throw new NotFoundHttpException("this tweet with id:".$id." not founded");
    }

    return $this->handleView($this->view($tweet));
}

/**
 * List One Hashtag to recommand
 * @Rest\Get("/tweets/recommanded-hashtag/group/{groupId}")
 * @param int $groupId
 * @return Response
 */
public function getHashtagToRecommand(int $groupId)
{
    $hashs = new ArrayCollection();
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $tweets = $repository->findHashtagToRecommand($groupId);

    if ($tweets == null){
        throw new NotFoundHttpException("this hashtag not founded");
    }

    foreach ($tweets as $key){
        $hashs->add($key->getHashtags());
    }

    return $this->handleView($this->view($hashs));
}

 /**
 * Create New Tweet
 * @Rest\Post("/tweet/add")
 *
 * @return Response
 */
public function postTweet(Request $request)
{
    $tweet = new Tweet();
    $form = $this->createForm(TweetType::class,$tweet);
    $data = json_decode($request->getContent(),true);
    $form->submit($data);
    if ($form->isSubmitted() && $form->isValid()){
        $em = $this->getDoctrine()->getManager();
        $em->persist($tweet);
        $em->flush();
        return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_CREATED));
    }

    return $this->handleView($this->view($form->getErrors()));
}

/**
 * Update Tweet
 * @Rest\Put("/tweet/update/{id}")
 * @param int $id
 * @return Response
 */
public function putTweet(Request $request, int $id)
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $existingTweet = $repository->find($id);
    if (null === $existingTweet) {
        throw new NotFoundHttpException();
    }
    $form = $this->createForm(TweetType::class, $existingTweet);
    $form->submit($request->request->all());

    if (false === $form->isValid()) {
        return $this->handleView($this->view($form->getErrors()));
    }

    $em = $this->getDoctrine()->getManager();
    $em->flush();

    return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_OK));
}

/**
 * Update Partially Tweet
 * @Rest\Patch("/tweet/patch/{id}")
 * @param int $id
 * @return Response
 */
public function patchTweet(Request $request, int $id)
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $existingTweet = $repository->find($id);
    if (null === $existingTweet) {
        throw new NotFoundHttpException();
    }
    $form = $this->createForm(TweetType::class, $existingTweet);
    $form->submit($request->request->all());

    if (false === $form->isValid()) {
        return $this->handleView($this->view($form->getErrors()));
    }
    $em = $this->getDoctrine()->getManager();
    $em->flush();

    return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_OK));
}

/**
 * Delete Tweet
 * @Rest\Delete("/tweet/{id}")
 * @param int $id
 * @return Response
 */
public function deleteTweet(int $id)
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $existingTweet = $repository->find($id);
    $em = $this->getDoctrine()->getManager();
    $em->remove($existingTweet);
    $em->flush();
    return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_NO_CONTENT));
}
}
...