execv
execv

Reputation: 849

CakePHP: Using the same layout

In my "CouponsController.php", I have the following 2 functions:

public function index() {
    $this->set('coupons', $this->Coupon->find('all'));
}

public function restaurants() {
    $this->set('coupons', $this->Coupon->findBycategory_id('1'));
    $this->render("index"); 
}

Basically, I want index function to return all coupons, and restaurants to return just category 1 (but I want to use the same view file).

I end up getting this errror:

Notice (8): Undefined index: Coupon [APP/View/Coupons/index.ctp, line 16]

It's because of how the array is returned for each of them. Here is my VIEW file and the results for each page:

Coupons/index.ctp:
foreach ($coupons as $c) {
    print_r($c);
}

INDEX function:
Array ( [Coupon] => Array ( [id] => 1 [vendor_id] => 1 [category_id] => 1 [title] => $10 For Whatever [price] => 10.00 [value] => 20.00 [start_at] => 2012-02-07 12:03:00 [end_at] => 2012-02-29 12:03:05 [details] => Test [terms] => Test [mini_views] => 0 [large_views] => 0 [created] => 2012-02-08 12:03:12 ) ) Array ( [Coupon] => Array ( [id] => 2 [vendor_id] => 2 [category_id] => 2 [title] => Test [price] => 100.00 [value] => 200.00 [start_at] => 0000-00-00 00:00:00 [end_at] => 0000-00-00 00:00:00 [details] => [terms] => [mini_views] => 0 [large_views] => 0 [created] => 2012-02-08 12:14:03 ) )

RESTAURANTS function:
Array ( [id] => 1 [vendor_id] => 1 [category_id] => 1 [title] => $10 For Whatever [price] => 10.00 [value] => 20.00 [start_at] => 2012-02-07 12:03:00 [end_at] => 2012-02-29 12:03:05 [details] => Test [terms] => Test [mini_views] => 0 [large_views] => 0 [created] => 2012-02-08 12:03:12 )

Upvotes: 1

Views: 96

Answers (1)

KukoBits
KukoBits

Reputation: 337

Well it's just how cakephp returns it, a turnaround would be

foreach ($coupons as $coupon) {
    $c = $coupon;
    if (isset($coupon["Coupon"])) { // if is set index in array ["Coupon"] {
        $c = $coupon["Coupon"];
    }
    print_r($c);
}

or

public function restaurants() {
    $params = array('conditions' => array('Coupon.category_id' => 1));

    $this->set('coupons', $this->Coupon->find('all', $params));
    $this->render("index"); 
}

Upvotes: 1

Related Questions