Wednesday, October 1, 2008

Re: Model arrays

Standardise your input to the Element.
Elements are designed for repeated content, or visual presentation of
similar data.

Either supply the Element with an array of manufacturers, or one
manufacturer.

Example for the Supply One Manufacturer to the element:
in the view:
<?php
// Only got one model data instance
echo $this->element('myElement', array('manufacturer' =>
$manufacturer));
// Got many data instances, but we're only supplying one to the
element
foreach ($manufacturers as $manufacturer) {
echo $this->element('myElement', array('manufacturer' =>
$manufacturer));
}
?>

The other approach is to always supply an array of manufacturers, and
render the list completely, rather than one instance at a time.
In this case, when you do a find and get a single data instance back,
just wrap it in an array to make it a list of one item

Controller Code:
<?php
// ...
function some_action($id = null) {
// If Many manufacturers are returned...
$this->set('manufacturers', $this->Manufacturers-
>find('all'));
// If only one is returned
$manufacturer = $this->Manufacturer->read(null, $id)
$this->set('manufacturers', array($manufacturer)); // Wrap
the single item in an array
}
// ...
?>

View code:
<?php
echo $this->element('myElement', $manufacturers);
?>


Best of luck with it.

On Oct 2, 6:03 am, nightfallvt <Kenneth.Mi...@gmail.com> wrote:
> For all of my models I created a table.ctp that can be used as an
> element in any view that needs to show a  table for that model. I'm
> trying to use the same element to display the table data in related
> models as well. Is there any way to reformat the array for a related
> model to match the format returned by the model's controller so I can
> use the same foreach in the table?
>
> Manufacturers returned by the vendors controller
> ($vendor['Manufacturer']):
> Array (
>     [0] => Array (
>         [id] => 150
>         ....
>
> Manufacturers returned by the manufacturer controller (index),
> ($manufacturers):
>
> Array (
>     [0] => Array (
>         [Manufacturer] => Array (
>             [id] => 150
>             ...
>
> Call from \vendors\view.ctp:
>
> echo $this->renderElement('..\manufacturers
> \table',array('manufacturers'=>$vendor['Manufacturer']));
>
> Part of \manufacturers\table.ctp:
>
> <?php
>     foreach ($manufacturers as $manufacturer){
>       echo $manufacturer['Manufacturer']['name'];
>     }
> ?>
>
> Thanks
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: