Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - How do i set the page title to an item name?

Tags:

php

cakephp

OK, so I'm trying to teach myself the CakePHP framework, and I'm trying to knock up a simple demo app for myself.

I have the controllers, views and models all set up and working, but I want to do something slightly more than the basic online help shows.

I have a guitars_controller.php file as follows...

<?php
class GuitarsController extends AppController {
    var $name = 'Guitars';
    function index() {
        $this->set('Guitars', $this->Guitar->findAll());
        $this->pageTitle = "All Guitars";
    }
    function view($id = null) {
        $this->Guitar->id = $id;
        $this->set('guitar', $this->Guitar->read());
        // Want to set the title here.
    }
}
?>

The 'Guitar' object contains an attribute called 'Name', and I'd like to be able to set that as the pageTitle for the individual page views.

Can anyone point out how I'd do that, please?

NB: I know that there is general disagreement about where in the application to set this kind of data, but to me, it is data related.

like image 819
ZombieSheep Avatar asked Oct 10 '08 18:10

ZombieSheep


2 Answers

These actions are model agnostic so can be put in your app/app_controller.php file

<?php
class AppController extends Controller {
    function index() {
        $this->set(Inflector::variable($this->name), $this->{$this->modelClass}->findAll());
        $this->pageTitle = 'All '.Inflector::humanize($this->name);
    }
    function view($id = null) {
        $data = $this->{$this->modelClass}->findById($id);
        $this->set(Inflector::variable($this->modelClass), $data);
        $this->pageTitle = $data[$this->modelClass][$this->{$this->modelClass}->displayField];
    }
}
?>

Pointing your browser to /guitars will invoke your guitars controller index action, which doesn't exist so the one in AppController (which GuitarsController inherits from) will be run. Same for the view action. This will also work for your DrumsController, KeyboardsController etc etc.

like image 188
neilcrookes Avatar answered Sep 27 '22 20:09

neilcrookes


You can set this in the controller:

function view($id = null) {
    $guitar = $this->Guitar->read(null, $id);
    $this->set('guitar', $guitar);
    $this->pageTitle = $guitar['Guitar']['name'];
}

Or in the view:

<? $this->pageTitle = $guitar['Guitar']['name']; ?>

The value set in the view will override any value that may have already been set in the controller.

For security, you must ensure that your layout / view that displays the pageTitle html-encodes this arbitrary data to avoid injection attacks and broken html

<?php echo h( $title_for_layout ); ?>
like image 31
Paolo Bergantino Avatar answered Sep 27 '22 21:09

Paolo Bergantino