0

I have that Entity TwitterPost.php

<?php

namespace FEB\TwitterBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Twitterpost
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="FEB\TwitterBundle\Entity\TwitterpostRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Twitterpost
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="titulo", type="string", length=50)
     * @Assert\NotNull(message="Debe escribir un titulo")
     */
    private $titulo;

    /**
     * @var string
     *
     * @ORM\Column(name="tweet", type="string", length=145)
     * @Assert\NotNull(message="Debe escribir un tweet")
     */
    private $tweet;


    /**
     * Many-To-Many, Unidirectional
     *
     * @var ArrayCollection $tags
     *
     * @ORM\ManyToMany(targetEntity="\FEB\TagsBundle\Entity\Tag")
     * @ORM\JoinTable(name="twitterpost_tags",
     *      joinColumns={@ORM\JoinColumn(name="twitterpost_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="tag", referencedColumnName="id")}
     * )
     */
    private $tags;


    /**
     * @var string
     *
     * @ORM\Column(name="photo", type="string", length=255, nullable=true)
     */
    private $photo;


    /**
     * @var string
     *
     * @ORM\Column(name="idpost", type="string", length=100)
     */
    private $idpost;

    /**
     * @var string
     *
     * @ORM\Column(name="autor", type="string", length=50)
     */
    private $autor;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime")
     */
    private $created;   


    public function __construct()
    {
        $this->setCreated(new \DateTime());
        $this->tags = new ArrayCollection();
    }


    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set titulo
     *
     * @param string $titulo
     * @return Twitterpost
     */
    public function setTitulo($titulo)
    {
        $this->titulo = $titulo;

        return $this;
    }

    /**
     * Get titulo
     *
     * @return string
     */
    public function getTitulo()
    {
        return $this->titulo;
    }

    /**
     * Set tweet
     *
     * @param string $tweet
     * @return Twitterpost
     */
    public function setTweet($tweet)
    {
        $this->tweet = $tweet;

        return $this;
    }

    /**
     * Get tweet
     *
     * @return string
     */
    public function getTweet()
    {
        return $this->tweet;
    }

    /**
     * Set tags
     *
     * @param string $tags
     * @return Twitterpost
     */
    public function setTags($tags)
    {
        $this->tags = $tags;

        return $this;
    }

    /**
     * Get tags
     *
     * @return string
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * Set photo
     *
     * @param string $photo
     * @return Twitterpost
     */
    public function setPhoto($photo)
    {
        $this->photo = $photo;

        return $this;
    }

    /**
     * Get photo
     *
     * @return string 
     */
    public function getPhoto()
    {
        return $this->photo;
    }

     /**
     * Set idpost
     *
     * @param string $idpost
     * @return Twitterpost
     */
    public function setIdPost($idpost)
    {
        $this->idpost = $idpost;

        return $this;
    }

    /**
     * Get idpost
     *
     * @return string 
     */
    public function getIdPost()
    {
        return $this->idpost;
    }

   /**
     * Set autor
     *
     * @param string $autor
     * @return Twitterpost
     */
    public function setAutor($autor)
    {
        $this->autor = $autor;

        return $this;
    }

    /**
     * Get autor
     *
     * @return string 
     */
    public function getAutor()
    {
        return $this->autor;
    }   

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Tag
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime 
     */
    public function getCreated()
    {
        return $this->created;
    }   
}

And this one

/**
 * Tag
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="FEB\TagsBundle\Entity\TagRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Tag
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="tag", type="string", length=255)
     */
    private $tag;

    /**
     * @var string
     *
     * @ORM\Column(name="autor", type="string", length=50)
     */
    private $autor;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime")
     */
    private $created;

    public function __construct()
    {
        $this->setCreated(new \DateTime());
    }   


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set tag
     *
     * @param string $tag
     * @return Tag
     */
    public function setTag($tag)
    {
        $this->tag = $tag;

        return $this;
    }

    /**
     * Get tag
     *
     * @return string 
     */
    public function getTag()
    {
        return $this->tag;
    }

    /**
     * Set autor
     *
     * @param string $autor
     * @return Tag
     */
    public function setAutor($autor)
    {
        $this->autor = $autor;

        return $this;
    }

    /**
     * Get autor
     *
     * @return string 
     */
    public function getAutor()
    {
        return $this->autor;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Tag
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime 
     */
    public function getCreated()
    {
        return $this->created;
    }
}

It's a Manytomany relationship between TwitterPost and Tags. And in my form has a select field which is a Entity class Tag.

<?php
namespace FEB\TwitterBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class TwitterpostType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('titulo')
                ->add('tweet', 'textarea')
                ->add('photo', 'file', array('required' => false))              
                ->add('tags', 'entity', array(
                                                'class' =>    'FEBTagsBundle:tag',
                                                'property' => 'tag',
                                                'empty_value' => 'Selecciona tags',
                                                'multiple' => true));               
    }
    public function getName()
    {
        return 'twitter_form';
    }
}

When I submit the data form, in the "twitterpost" table the data is saved correctly and in the aux table "twitterpost_tags" too.

For example:

twitterpost_id tag_id
1-----------1
1-----------2
2-----------1
2-----------3
The tag table:
id---------tag
1----------tagA
2----------tagB
3----------tagC

When I want show all data of Twitterpost, what is the best approached to show the tag name and not the tag id?

Than you in advanced.

cmaciasg
  • 71
  • 2
  • 11
  • I wonder if there is any way to insert in database this: `twitterpost_id tag_id 1-----------tagA 1-----------tagB 2-----------tagA 2-----------tagC` Instead of this: `twitterpost_id tag_id 1-----------1 1-----------2 2-----------1 2-----------3` – cmaciasg Aug 13 '13 at 12:40

1 Answers1

0

I'm not sure if I get you right. To show All tags in the twitterpost form you are already doing the right thing:

    ->add('tags', 'entity', array(
          'class' =>    'FEBTagsBundle:tag',
          'property' => 'tag',
          'empty_value' => 'Selecciona tags',
          'multiple' => true
));

This will create a multiple select box where you can select from all the tags. From the docs:

property

type: string

This is the property that should be used for displaying the entities as text in the HTML element. If left blank, the entity object will be cast into a string and so must have a __toString() method.

If you don't want a multi-select but checkboxes or radiobuttons instead, checkout this part of the documentation.


In case you are asking on how to output the data when not inside the TwitterpostType, you can just treat them as objects in a Controller:

$repository = $this->getDoctrine()->getRepository('TwitterBundle:Twitterpost');
$post = $repository->findOne($id);

// to get all _tags_ of a post just call the getter:
$tags = $post->getTags();

The same goes for twig templates:

{# imagine you have all posts in a variable called 'posts' #}
{% for post in posts %}
     <h1>{{ post.titulo }}</h1>
     <div class="tags">
         {% for tag in posts.tags %}
         {{ tag.tag }}
         {% endfor %}
     </div>
{% endfor %}

Edit:

For a native SQL / DQL query you need a custom repository class. There you can store your own queries:

class TwitterpostRepository extends EntityRepository
{
    public function findAllOrderedByName()
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT p FROM TwitterBundle:Twitterpost p ORDER BY p.name ASC'
            )
            ->getResult();
    }
}

Then you can use it like this in the controller:

$repository = $this->getDoctrine()->getRepository('TwitterBundle:Twitterpost');
$post = $repository->findAllOrderedByName();
ferdynator
  • 6,245
  • 3
  • 27
  • 56
  • First of all, thankyou for your response. Yes, I meant how to ouput the data and It works perfectly. But I have a question. This approach is good when I want to output the Type data, ok, what if I wanted to make a NativeSql like a UNION instead findOne()? In this case I could not use this method, no? – cmaciasg Aug 14 '13 at 05:51
  • Hi again!!! I have this: `return $this->getEntityManager() ->createQuery( 'SELECT t.id FROM TwitterBundle:Twitterpost t UNION SELECT f.id FROM FacebookBundle:Facebookpost f' ) ->getResult();` And I got this error: [Syntax Error] line 0, col 48: Error: Expected end of string, got 'UNION' – cmaciasg Aug 14 '13 at 11:14
  • Check out [this question](http://stackoverflow.com/questions/4155288/how-to-write-union-in-doctrine-2-0) and [this one](http://stackoverflow.com/questions/7981549/sql-query-with-union-in-doctrine-symfony). If they don't solve your problem, create a new question please. – ferdynator Aug 14 '13 at 11:58