geoB
geoB

Reputation: 4704

Symfony2: sort an ArrayCollection

According to this one should use OrderBy to sort an ArrayCollection. Somehow the following does not achieve this result when listing the collection of contact dates for a household:

Household entity (snippet)

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\OneToMany(targetEntity="Mana\ClientBundle\Entity\Contact", mappedBy="household")
 * @ORM\OrderBy({"contact_date" = "DESC"})
 */
private $contacts;

Contact entity (snippet)

    /**
     * Contact
     *
     * @ORM\Table(name="contact", indexes={@ORM\Index(name="idx_contact_household_idx", columns={"household_id"}), @ORM\Index(name="idx_contact_type_idx", columns={"contact_type_id"}), @ORM\Index(name="idx_contact_center_idx", columns={"center_id"})})
     * @ORM\Entity
     */
    class Contact
    {
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="IDENTITY")
         */
        private $id;

        /**
         * @var \DateTime
         *
         * @ORM\Column(name="contact_date", type="date", nullable=true)
         */
        private $contactDate;
        ...
    }

Template (for 5 most recent?) (snippet)

{% for i in 0..4 %}
{% if household.contacts[i] is defined %}
<tr><td>{{ household.contacts[i].contactDate|date('m/d/Y') }}</td>
...{% endif %}
{% endfor %}

Sample result

Date    
05/02/2012
05/23/2012
05/30/2012
06/26/2012
06/06/2012

Upvotes: 0

Views: 3563

Answers (1)

Michael Sivolobov
Michael Sivolobov

Reputation: 13240

Your problem in the field name. As I can see form your Contact entity your field is named as $contactField but @ORM\OrderBy({"contact_date" = "DESC"}) from your Houshold entity use column name instead of field name. I think that if you change your contact_date to contactDate it will be working.

It is very strange that you have no error from Doctrine about this issue. Because Doctrine usually operate with fields but not columns.

Upvotes: 1

Related Questions