In my app a user has a profile and a user can post comments and posts.
When viewing a list of comments for a post I want to show the name of the person that posted the comment. I have tried the following:
<?php if ( ! empty($post['Comment']) ): ?>
<ul>
<?php foreach ($post['Comment'] as $comment): ?>
<li id="comment-<?php echo $comment['id']; ?>">
<h3><?php echo $this->Html->link($comment['User']['Profile']['firstname'] . ' ' . $comment['User']['Profile']['lastname'], array('controller'=>'profiles','action'=>'view','userName'=>$comment['User']['username'])); ?></h3>
<?php echo $comment['content']; ?>
<?php echo $comment['datetime']; ?>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>No comments...</p>
<?php endif; ?>
But I get the following error: Undefined index: User [APP/View/Posts/view.ctp, line 37]
Any ideas on how to fix the issue?
I have the following for the controller method:
function view ( $id = null, $slug = null )
{
$post = $this->Post->find('first',array('contain'=>array('Comment','User'=>array('Comment','Profile')),'conditions'=>array('Post.id'=>Tiny::reverseTiny($id))));
if (!$post)
{
throw new NotFoundException('404');
}
else if($post['Post']['status'] == '0') // 0=draft 1=open 2=open
{
if($post['Post']['user_id'] == $this->Auth->user('id'))
{
$this->Session->setFlash('Your post has NOT been published yet');
}
else
{
throw new NotFoundException('404');
}
}
if (Inflector::slug($post['Post']['title']) != $slug || $slug = null)
{
$this->redirect(array('id'=>Tiny::toTiny($post['Post']['id']),'slug'=>Inflector::slug($post['Post']['title'])));
}
$this->set(compact('post'));
}
The model associations should all be correct as I can see the comments fine and see the profile info for the post itself, it's just the comments that don't show the profile info.
Thanks to all who can help.
You're setting $post['Comment'] as $comment in your foreach, whilst your user data isn't in $post['Comment']['User'] but in $post['User'], so your call with $comment['User'] won't work, since that index does not exist.
Use debug($var) in the future so you can see how your array structure looks like at any given moment.
Related
I've got a few fields on a property site, grabbing a value in English & depending on the value, translating it (if another language other than English is selected).
This piece of code works fine:
<?php if(get_post_meta($post->ID,'prop_parking',true) && $prop_parking):
$prop_parking_meta = get_post_meta($post->ID,'prop_parking',true);
if ($prop_parking_meta == 'Yes') {
$prop_parking_meta = '<!--:en-->Yes<!--:--><!--:es-->Sí<!--:--><!--:ru-->да<!--:-->';
}
elseif ($prop_parking_meta == 'No') {
$prop_parking_meta = '<!--:en-->No<!--:--><!--:es-->No<!--:--><!--:ru-->нет<!--:-->';
} ?>
<li>
<p><?php echo PROP_PARK_CSTM;?>:</p><p> <?php _e( $prop_parking_meta ); ?></p>
</li>
<?php endif; ?>
I get back Yesin the set language, yet in this field I don't (I just see Yes or No):
<?php if(get_post_meta($post->ID,'prop_garage',true) && $prop_garage):
$prop_garage_meta = get_post_meta($post->ID,'prop_garage',true);
if ($prop_garage_meta == 'Yes') {
$prop_garage_meta = '<!--:en-->Yes<!--:--><!--:es-->Sí<!--:--><!--:ru-->да<!--:-->';
}
elseif ($prop_garage_meta == 'No') {
$prop_garage_meta = '<!--:en-->No<!--:--><!--:es-->No<!--:--><!--:ru-->нет<!--:-->';
} ?>
<li>
<p><?php echo PROP_GARG_CSTM;?>:</p><p> <?php _e( $prop_garage_meta ); ?></p>
</li>
<?php endif; ?>
Is it something obvious I'm missing? :( Thanks!
I don't know why this issue happens sometimes in qTranslate, but there are two options to deal with it:
using the shortcode notation
$prop_garage_meta = '[:en]Yes[:es]Sí[:ru]да';
applying the_content filter
$prop_garage_meta = apply_filters(
'the_content',
'<!--:en-->Yes<!--:--><!--:es-->Sí<!--:--><!--:ru-->да<!--:-->'
);
I am using the WordPress plugin WP-PostViews to display the number of views a post has. I am using this code and it works great:
<?php if(function_exists('the_views')) { the_views(); }?>
The thing I want to do is to use this number of post views as a variable but I can't get it working. So far I have tried:
<?php if(function_exists('the_views')) { $variable = the_views(); } ?>
and
<?php if(function_exists('the_views')) { $variable = the_views(); } else { $var = 0; } ?>
No success so far. Does anyone have suggestions?
By default the_views() echos instead of returns. You can get a return by setting the first argument to false. Example:
<?php if(function_exists('the_views')) { $variable = the_views(false); } ?>
I'm displaying all the posts in the category that have a valid date as follows -
<?php $blog = $pages->find('posts');
foreach($blog->children() as $blogpost): ?>
<?php if ($blogpost->title() <= $latest && $blogpost->category == $thisCat): ?>
//HTML for displaying post goes here
<?php endif ?>
<?php end foreach ?>
That works fine when those posts validate my condition, and displays nothing if it doesn't. What I want to do is display an error message (like 'there are no posts here') when there are no posts that pass the condition. I can't just do a simple else condition in that if query because it's inside the foreach loop. I can't take the if query out of the foreach loop because it relies on a variable that is defined as part of it ($blogpost).
Kind of stuck in this catch 22... Any suggestions?
How about...
<?php
$blog = $pages->find('posts');
$found_something = false;
foreach($blog->children() as $blogpost) {
if ($blogpost->title() <= $latest && $blogpost->category == $thisCat) {
$found_something = true;
//HTML for displaying post goes here
}
}
if(!$found_something) {
// display error message
}
?>
By the way, is there a specific reason why you're using the alternative PHP syntax?
I'd create a counter variable which increments each time when you display a post.
<?php $blog = $pages->find('posts');
$displayedPosts = 0;
foreach($blog->children() as $blogpost): ?>
<?php if ($blogpost->title() <= $latest && $blogpost->category == $thisCat):
$displayedPosts++; ?>
//HTML for displaying post goes here
<?php endif ?>
<?php end foreach ?>
<?php
if ($displayedPosts == 0) {
echo 'ERROR!';
}
?>
Using a boolean variable (as tmh did) is probably better in this case unless you want to count the posts.
Just count your posts , if it's 0 display just the message , else execute foreach loop :
<?php $blog = $pages->find('posts');
if(count($blog->children())==0){ echo 'No post Here'; }
else{
foreach($blog->children() as $blogpost): ?>
<?php if ($blogpost->title() <= $latest && $blogpost->category == $thisCat): ?>
//HTML for displaying post goes here
<?php endif ?>
<?php end foreach ?>
<?php } ?>
I'm using a custom field template plugin for WP. I want to hide
<li>Sqft: [squareft]</li>
if the field is empty. I've tried different codes, these are two I've tried based on suggestions:
<?php if ('squareft' !== '') { ?><li>Sqft: [squareft]</li>
<?php } ?>
And
<?PHP $squareft = ('squareft'); if ($squareft != '') { echo '<li>Sqft: [squareft]
</li>';} if (empty($squareft)) { echo " "; } ?>
I obviously don't have a clue what I'm doing, although I'm learning through trial and error. It uses shortcodes, so [squareft] is what to use to output the field data.
Any help is appreciated.
Update:
I think I've got it working, based on doing this method. Not yet gone live but it's working in my test post.
<?php
global $post;
$bathrooms = get_post_meta($post->ID, 'bathrooms', true);
if ( !empty($bathrooms) ) { echo '<li>Baths: [bathrooms]</li> | ' ; }
?>
Try this (replacement of the if statement in your first code sample):
<?php if (do_shortcode('[squareft]') != '') { ?>
<li>Sqft: [squareft]</li>
<?php } ?>
Or if you know the custom meta field's actual field name (generated by the plugin, probably some kind of prefix + squareft) you can do:
<?php if (get_post_meta($post->ID, 'squareft', true) != '') { ?>
It would help to know the specific plugin you are using.
Using the get custom fields plugin I have used the following to hide content if the field it empty (in this case the 'info' field):
<?php $info = c2c_get_custom('Info');?>
<?php if ( $info == "" ) {echo "";} else {echo "<h2 id=comments>Notes</h2><div id=info>$info</div>" ;} ?>
Not sure if this will help but it might give someone else more ideas.
Are tring this :
<?php if ( (c2c_get_custom('image')) ) { ?>
blah blah blah php code etc...
<?php } ?>
Works perfectly. If field has something it shows, if not no show, it was leaving a broken image when empty, now its good.
<?php if (get_post_meta($post->ID, 'squareft', true) != '') { echo "display output";?>
I am relatively new to The Zend framework having only been working with it probably two months at the most. I am now trying to get a list of results from a query I run, send it through the zend paginator class and display 4 results per page, however it does not seem to be recognising when it has got 4 results, I believe there is an error in my code but I can not for the life of me see it, I was hoping someone here will be able to pick up on it and help me and out and probably tell me it is something stupid that I have missed. Thanks here is the code I have written.
This the query in my model
public function getAllNews()
{
$db = Zend_Registry::get('db');
$sql = "SELECT * FROM $this->_name WHERE flag = 1 ORDER BY created_at";
$query = $db->query($sql);
while ($row = $query->fetchAll()) {
$result[] = $row;
}
return $result;
}
This is code in my controller
function preDispatch()
{
$this->_helper->layout->setLayout('latestnews');
Zend_Loader::loadClass('newsArticles');
$allNews = new newsArticles();
$this->view->allNews = $allNews->getAllnews();
//die (var_dump($this->view->allNews));
$data = $this->view->allNews;
// Instantiate the Zend Paginator and give it the Zend_Db_Select instance Argument ($selection)
$paginator = Zend_Paginator::factory($data);
// Set parameters for paginator
$paginator->setCurrentPageNumber($this->_getParam("page")); // Note: For this to work of course, your URL must be something like this: http://localhost:8888/index/index/page/1 <- meaning we are currently on page one, and pass that value into the "setCurrentPageNumber"
$paginator->setItemCountPerPage(1);
$paginator->setPageRange(4);
// Make paginator available in your views
$this->view->paginator = $paginator;
//die(var_dump($data));
}
Below is the view that builds the paginator,
<?php if ($this->pageCount): ?>
<div class="paginationControl">
<!-- Previous page link -->
<?php if (isset($this->previous)): ?>
< Previous |
<?php else: ?>
<span class="disabled">< Previous</span> |
<?php endif; ?>
<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<?= $page; ?> |
<?php else: ?>
<?= $page; ?> |
<?php endif; ?>
<?php endforeach; ?>
<!-- Next page link -->
<?php if (isset($this->next)): ?>
Next >
<?php else: ?>
<span class="disabled">Next ></span>
<?php endif; ?>
</div>
<?php endif; ?>
And finally the code the makes up my view
<div id="rightColumn">
<h3>Latest News</h3>
<?php if (count($this->paginator)): ?>
<ul>
<?php foreach ($this->paginator as $item): ?>
<?php
foreach ($item as $k => $v)
{
echo "<li>" . $v['title'] . "</li>";
}
?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?= $this->paginationControl($this->paginator, 'Sliding', '/latestnews/partial_pagination_control.phtml'); ?>
</div>
I will be greatful for any help you can give me.
Thanks
Sico
$paginator should be set to 4 as you want to show only 4 records at a time :
$paginator->setItemCountPerPage(4);
So I think the root of your problem is in your model class with the getAllNews function. The Zend_Db fetchAll function retrieves an associative array of all the records matching your query. You are returning an array of one element that is an array of all the rows retrieved by your select statement.
Try this:
public function getAllNews()
{
$db = Zend_Registry::get('db');
$sql = "SELECT * FROM $this->_name WHERE flag = 1 ORDER BY created_at";
return $db->fetchAll($sql);
}
You sould not pass values to paginator if you want it to limit your query.
There is a code will work for you
$usersTable = $this->getTable();
$registerSelect = $usersTable->select()->where('status = ?', 'OK')->order('lastLogin DESC');
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($registerSelect));
$paginator->setCurrentPageNumber($page);
$paginator->setItemCountPerPage($limit);