I’ve started a project in CakePHP. I have no experience of it, most of my experience is with Symfony2.
Right now, I have built a view file, a controller, and a model for use with this project and it’s database. In one controller I want to pass one record from the database to the view for use on the homepage. However, I’m unable to pass the record as I get this error:
Notice (8): Undefined variable: content [APP\View\Contents\home.ctp,
line 42]
Here is my controller code:
function home() {
$content = $this->Content->query("SELECT title, content FROM content WHERE id = 1;");
$this->set('pagecontent',$content);
}
And here is the code I’m using to display the data in the view file:
<?php $content['content']; ?>
What have I missed?
EDIT:
I have changed the <?php $content['content']; ?> to <?php echo $pagecontent['Content']['content']; ?> inline with the changes outlined in the answer from Ross. However, there is now this error:
Notice (8): Undefined index: Content [APP\View\Contents\home.ctp, line
43]
I have used the <?php echo debug($this->viewVars); ?> and this is the output from that:
app\View\Contents\home.ctp (line 42) Array (
[pagecontent] => Array
(
[0] => Array
(
[content] => Array
(
[title] => <h1>This is a title</h1>
[content] => <p>this is some test text</p>
)
)
)
)
$this->set('pagecontent',$content);– this is where you are setting view variables.You are trying to access a variable called
$content, when in fact it is stored as$pagecontent.Also based on Cake conventions, the key
contentshould actually beContent, so your output should probably be:You can always do
debug($this->viewVars);to see exactly what you have access to.Seeing the output helps; the error is due to how cake is returning the data.
This is likely due to you using
query()rather thanfind()orread(). (also explains why yourcontentkey is lowercase –query()uses the table name, rather than the model name.Try:
should now work.
The alternative is to just access the data through the array index:
echo $pagecontent[0]['content']['title']which isn’t as “cake” like.
to expand =
query()returns data in a different structure than usingfindorread. There’s other ways you can do this too.should also be valid.