2

A bit of a tricky one:

I have a form collection for the Entity Street. The collection items are the houses. I need to order the houses in the collection by the room

I had tried to add @ORM\OrderBy({"room" = "ASC"}) but obviously without specifying the weight fields inside the Room Entity there is no way the collection will know.

Is what I am trying to do even possible?

Street.php

/**
 * @var ArrayCollection
 *
 * @ORM\OneToMany(targetEntity="houses", mappedBy="street")
 */
protected $houses;

Houses.php

/**
 * @var Room
 *
 * @ORM\ManyToOne(targetEntity="Room", inversedBy="house")
 * @ORM\JoinColumn(name="room_id", referencedColumnName="id")
 */
private $room;

/**
 * @var Street
 *
 * @ORM\ManyToOne(targetEntity="Street", inversedBy="houses")
 * @ORM\JoinColumn(name="street_id", referencedColumnName="id")
 */
private $street;

HouseCollectionType.php

 $builder
        ->add('houses', 'collection', array(
            'type'          => new HouseFieldsType(),
            'allow_delete'  => false,
        ))
    ;

 public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    $resolver->setDefaults(array(
        'data_class' => 'Bundle/Street'
    ));
    }
user742736
  • 2,629
  • 5
  • 30
  • 40
  • 1
    Maybe [this post](https://stackoverflow.com/questions/22828669/ordering-doctrine-collection-based-on-associated-entity-when-it-is-not-possible) will help. – chapay Oct 30 '15 at 19:27
  • Thanks @chapay, the solutions on the post you provided are very helpful, issue with my issue is I needed it to work with the form collection so it can do the setter and getter automatically. – user742736 Oct 31 '15 at 06:33

1 Answers1

-1

I don't know if this is the right way but here it goes:

Street.php

public function getHouses()
{
    $orderedHouse = array();
    /** @var House $house */
    foreach($this->houses as $house) {
        $orderedHouses[$house->getRoom()->getWeight()] = $house;
        $this->houses->removeElement($house);
    }
    ksort($orderedHouses);
    foreach($orderedHouses as $house) {
        $this->houses->add($house);
    }
    return $this->houses;
}
user742736
  • 2,629
  • 5
  • 30
  • 40
  • It will be very helpful if you could provide feedback with the negative as a negative without feedback doesn't help with the solution – user742736 Oct 31 '15 at 06:30