phpcakephpform-helpers

How to iterate through object array with form helpes in cakephp?


I have an object CuratedPage with property pageName.

I am creating an array of CuratedPage objects in controller and setting it for the view like this:

$this->set('curatedPages', $curatedPages);

In the view I am creating a dropdown of page names like this:

$pageNames = array();
foreach($curatedPages as $curatedPage) {
    array_push($pageNames, $curatedPage->getPageName());
}
echo $this->Form->input('curatedPage', array('options' => $pageNames));

Is there a way in cakephp that will allow me to pass the array of CuratedPage objects to the Form->input(...) instead of creating an array of scalar values.


Solution

  • I'm not sure what you would expect the form helper to do in that case. However, depending on your PHP version (>= 5.2.0 required) the magic __toString() method might do it. If you implement it to return the pagename, then you would end up with the same result as with your posted snippet, ie an numerical indexed (the value attribute) HTML option list with the page names as labels.

    However, implementing this only for that purpose in this specific view seems wrong to me, you're probably better of utilizing a custom helper, or as @BrianGlaz suggested prepare the data in the controller.