form sort elements

How can I sort form elements in form? for render with foreach in view. Because when I add elements dynamically they add to end of array. It's real?

@xAockd it depends on which criteria you want to sort them.

According to the documentation Phalcon form cant be sorted.

But you can sort your element before adding the to the form. See:


   // firstly create an array

   /* fill it dinamycally with your elements
    $listOfDinamycFormElements[]=new Element(...);

  // now you can use php built in functions to sort arrays
   // lets say you want to sort them on the alpha order
        return strcmp($a->getName(),$b->getName());

   $form = new Phalcon\Forms\Form();

  // finaly add them to the form
  foreach($listOfDinamycFormElements as $elm){

PHP sort functions :


I'm add specific attrib to sort them. I try usort earlier - not work.

My code was:

usort($form->getElements(), function($a, $b){ return ($a->getAttribute('data-sort') < $b->getAttribute('data-sort')) ? -1 : 1; });


that's normal, you are trying to use an object as if it was an array. Also the form object doesnt extend arrayObject then you cant use php built in functions for that. That's why i said you to sort your elements before adding them to the form.

Eventually, if you feel comfortable with php OOP, you can use your one extends and access the form array directly from within the object (only possible if it is not private).