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:

<?php

   // firstly create an array
    $listOfDinamycFormElements=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
   usort($listOfDinamycFormElements,function($a,$b){
        return strcmp($a->getName(),$b->getName());
   });


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

  // finaly add them to the form
  foreach($listOfDinamycFormElements as $elm){
      $form->add($elm);
  }

PHP sort functions : http://fr2.php.net/manual/en/array.sorting.php



8.5k

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; });

@xAockd

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).