<?php
$radifHa = array();
foreach ($akhbars as $akhbar) {
$radif = array();
$radif[] = $this->Html->tag('h4', h($akhbar['Akhbar']['onvan']));
$radifInfo = array();
$radifInfo[] = h($akhbar['Akhbar']['created']);
$radifInfo[] = $this->Html->tag('span', ':', array('class' => 'separator'));
$radifInfo[] = 'by';
$radifInfo[] = $this->Html->link($akhbar['User']['esmekochak'], array('controller' => 'users', 'action' => 'view', $akhbar['User']['id']));
$radifInfo[] = $this->Html->tag('span', ':', array('class' => 'separator'));
$radifInfo[] = '0 comments';
$radif[] = array(implode(' ', $radifInfo), array('class' => 'post_info'));
$radif[] = $this->Html->div('desc_block', h($akhbar['Akhbar']['kholase']));
}
$radifHa[] = $radif;
if (!empty($radifHa)) {
echo $this->Html->div('blog_post', h($radifHa));
}
?>
I'm getting this error
Notice (8): Array to string conversion [CORE\Cake\View\Helper\HtmlHelper.php, line 928]
How can I fix this?
I'm in the index view of Akhbar.
Fixing with this alternative code, but I want to fix with the above code, can I?
<?php foreach ($akhbars as $akhbar): ?>
<div class="blog_post">
<h4><?php echo h($akhbar['Akhbar']['onvan']);?></h4>
<div class="post_info">
<?php echo h($akhbar['Akhbar']['created']);?>
<span class="separator">:</span>
By:<?php echo $this->Html->link($akhbar['User']['esmekochak'], array('controller' => 'users', 'action' => 'view', $akhbar['User']['id']));?>
<span class="separator">:</span>
0 comments
</div>
<div class="desc_block"><?php echo h($akhbar['Akhbar']['kholase']); ?></div>
</div>
<?php endforeach; ?>
You're not telling us exactly what line gives you that error (in the view, not the helper), but the error itself does tell you a lot about what is happening. You are simply passing an array where a string should be passed.
Html->div accepts Html->div(string, string, array), and you are doing
echo $this->Html->div('blog_post', h($radifHa));
Now, . The h() function says
string|array|object $text Text to wrap through htmlspecialchars.
Also works with arrays, and objects. Arrays will be mapped and have
all their elements escaped. Objects will be string cast if they
implement a __toString method. Otherwise the class name
will be used.
You are passing an array to h(), you will get a mapped array with the element escaped. You can see the code for that function here. Line 177, it returns an array. An since Html->div doesn't like arrays as second parameters, well, it complains.
What can you do? Don't use an array. Either flatten the array yourself before using div, or organize that string some other way instead of in an array (like concatenating the resulting strings in a foreach instead of storing them in $radifHa).
Related
I have made a custom taxonomy archive page called taxonomy-country.php. The file runs perfectly and loops through the current country and displays the posts within it.
Above this loop on the same templeate I want to display a map of all the post locations using Advanced Custom Fields. I've used the code before with no problems but not in an archive file, however when used at the top of the template the map and markers show fine but the standard archive loop no longer displays.
What is wrong with the wpquery that it kills the loop after it? Or is there another reason I can't run he query above the normal loop on an archive page?
<?php
// WP_Query arguments
$args = array (
'post_type' => 'home',
'order' => 'ASC',
'orderby' => 'title',
'posts_per_page' => '-1',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) { ?>
<div class="acf-map">
<?php while ( $query->have_posts() ) {
$query->the_post(); ?>
<?php
$location = get_field('location');
if( !empty($location) ):
?>
<div class="acf-map">
<div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">
<h2 class="name"><?php the_title(); ?></h2>
<strong class="number"><?php echo do_shortcode('[mrp_rating_result rating_form_id="2"]'); ?></strong>
</div>
</div>
<?php endif; ?>
<?php }
} else {
// no posts found
}
// Restore original Post Data
wp_reset_query() ?>
UPDATE:
Just found out this should be shorter alternative:
wp_reset_postdata()
ORIGIONAL:
This line killed it:
// Restore original Post Data
wp_reset_query() ?
Reason: You did not use main $wp_query, hence $query->the_post() did not interfere with the current index of $wp_query. Resetting it will cause the main loop to restart.
Reference: https://codex.wordpress.org/Function_Reference/wp_reset_query
A safer way is to:
Before the category loop:
global $post;
$temp_post = $post;
After the category loop:
$post = $temp_post;
Just 3 lines and it should work.
Cheers!
As per above answer you have to store the $post in in temporary variable and restore it before wp_reset_query()
example function code look like below
function cd_meta_box_cb_hotel( $post )
{
global $post;
$temp_post = $post;
$selected=get_post_meta($post->ID, 'hotel_location_id',true);
$mquery = new WP_Query(array(
'post_type' => 'custom posttype',
'post_status' => 'publish',
'posts_per_page' => -1,
));
while ($mquery->have_posts()) {
$mquery->the_post();
// doing what you need
}
**$post = $temp_post;
wp_reset_query();**
}
I have 2 views, postview.ctp and usercomment.ctp, calling the same comment.ctp element. This element shows image using UploadPack helper. But image on usercomment.ctp doesn't show and has this error message
Notice (8): Undefined index: User [APP\Plugin\upload_pack\Model\Behavior\UploadBehavior.php, line 222]
line 222: $settings = self::$__settings[$modelName][$field];
The self::$__settings in usercomment.ctp is empty , but in postview.ctp it's not empty and the image showed up correctly.
comment.ctp:
<?php echo $this->Html->link($this->upload->image(
$comment['User'],
'User.avatar',
array('style' => 'thumb'),
array('class' => array('img-responsive', 'img-rounded'))
),
array('controller' => 'users',
'action' => 'view',
$comment['User']['id']),
array('escape' => false)
) ?>
And this is code to call comment.ctp on from the both view.
<?php if (!empty($comments)): ?>
<?php foreach ($comments as $comment): ?>
<?php echo $this->element('comment',array('comment' => $comment));?>
<?php endforeach; ?>
<?php endif; ?>
I've checked the $comment array and they're identical. How to fix it?
Load User model on usercomment action in Comment controller.
public function usercomments($id) {
$this->loadModel('User');
if($this->Auth->loggedIn()){
.....
I'm just trying to get my head around Kohana, so if I'm going about this the wrong way, let me know!
I want to group results in my output. The way I did this in vanilla-PHP / PDO was to prepare a query, and then execute it within the output results. I can't get there in Kohana (3.2.2), though.
In this case, on my 'terms' page, I want to group 'terms' by 'type', with each group of terms separated by a 'type' header.
My 'terms' controller is (simplified):
class Controller_Terms extends Controller {
public function action_index()
{
$view = View::factory('terms');
// types of term - for grouping terms together
$sql = 'SELECT DISTINCT Type
FROM Term';
$view->types = DB::query(Database::SELECT, $sql)->as_object()->execute();
// list of terms - executed separately for each type
$sql = 'SELECT TermId, Term
FROM Term
WHERE Type = :type';
$view->terms = DB::query(Database::SELECT, $sql)->as_object();
$this->response->body($view);
}
}
And the 'terms' view includes (simplified):
<? foreach ($types as $type): ?>
<h2><?= $type->Type ?></h2>
<? $params = array(':type' => $type->Type);
$terms->parameters($params)->execute();
foreach ($terms as $term): ?>
<?= $term->Term ?>
<? endforeach // term ?>
<? endforeach // type ?>
I get the 'type' headers ok, but I don't get any terms within each type.
Any suggestions appreciated!
execute() returns a special object (Database_Result), so you need something like this:
$items = $terms->parameters($params)->execute();
foreach ($items as $term): ?>
...
In my hook_preprocess_node function I am changing the links by themeing and adding a t() function to allow translation.
The problem is when I render out in my node I get the word "ARRAY" printed out, this is using either
<?php print render($field_downloads); ?> or <?php print $field_downloads); ?>
in my node.
Code in template.php
$list_of_paths = array();
foreach($field_downloads as $index => $data)
{
$file_uri = $data['uri'];
$file_path = file_create_url($file_uri);
$list_of_paths[] = '<strong> >>'. t('DOWNLOAD'). '</strong> '.l(t($data['description']), $file_path);
}
$variables['field_downloads'] .= theme("item_list", array(
'items' => $list_of_paths,
'type' => 'ul',
'attributes' => array('class' => 'downloads'),
));
}
My objective is to display records for a related child model (once removed) in the view. My problem is that I receive a 'Notice (8): Undefined index:' error message when I try to output the following query.
Tournaments have many tournamentDetails, and tournamentDetails have many updates. I'm trying to display all the updates for each tournamentDetail that is displayed on the tournaments view.
So my question is how to properly resolve the error message and display the updates for each tournamentDetail on the tournaments view page.
My find data in the 'tournaments' controller view action is:
$updates = $this->Tournament->TournamentDetail->Update->find('all', array( 'tournament_details.tournament_id'=> $this->data['Tournament']['id']));
In the view, I have this code.
<?php foreach ($tournament['Update'] as $update): ?>
<h3>Updates</h3>
<h1><?php echo $update ['title']; ?></h1>
<p><?php echo $update ['body']; ?></p>
<hr/>
<?php endforeach; ?>
This is the same 'foreach' code the I use for the other related child records without problem. I did use the debug() function to investigate but didn't see what I was missing.
The output of the $updates array from the debug function looks like this:
Array
(
[0] => Array
(
[Update] => Array
(
[id] => 1
[title] => first round matches start today
[date] => 2010-03-19
[body] => this tournament's first round matches start today.
[tournament_detail_id] => 4
[homeStatus] => no
)
Is there a special way to display records this deep?
As always, thanks in advance.
Paul
Update: Feb 23/11
After some testing the problem I seem to have is finding and passing the correct value to the $updates variable;
To summarize, I want the $updates variable to hold the current 'tournament_details_id'. This will then display the related update records in the 'tournaments' view.
I'm still a beginner and most likely overlooked the obvious.
Here is the model info:
class Tournament extends AppModel {
var $name = 'Tournament';
var $hasMany = array(
'TournamentDetail' => array(
'className' => 'TournamentDetail',
'foreignKey' => 'tournament_id',)
class TournamentDetail extends AppModel {
var $name = 'TournamentDetail';
var $belongsTo = array(
'Tournament' => array(
'className' => 'Tournament',
'foreignKey' => 'tournament_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
class Update extends AppModel {
var $name = 'Update';
var $belongsTo = array(
'TournamentDetails' => array(
'className' => 'TournamentDetails',
'foreignKey' => 'tournament_detail_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Controller data:
class TournamentsController extends AppController
function view($slug = null) {
if (!$slug) {
$this->Session->setFlash(__('Invalid Tournament.', true));
$this->redirect(array('action'=>'index'));
}
$this->Tournament->recursive = 1;
$tournament = $this->Tournament->findBySlug($slug);
$updates = $this->Tournament->TournamentDetail->Update->find('all', array('conditions' => array( 'tournament_details_id' => $this->data['TournamentDetails']['id'] )));
$this->set(compact('tournament','updates', $updates ));
Tournament view. This is display the 'tournament details' and (ideally) related tournament detail 'updates'
<h2><?php echo $tournament['Tournament']['name']; ?></h2>
<?php foreach ($tournament['TournamentDetail'] as $tournamentDetail): ?>
<h1><?php echo $tournamentDetail ['title']; ?></h1>
<p><?php echo $tournamentDetail ['body']; ?></p>
<?php endforeach; ?>
<?php foreach ($updates['Update'] as $update): ?>
<h4>Update: <?php echo $update ['date']; ?></h4>
<p> <?php echo $update ['Update'] ['title']; ?></p>
<p><?php echo $update ['Update'] ['body']; ?></p>
<?php endforeach; ?>
I've tested this by adding in the tournament details 'id' as an integer and it pulls up the correct 'update' record. However I seem to have problems configuring the find operation to do the same.
As always I appreciate the help.
Thanks
Paul
Based on your debug output, it seems that your $tournaments variable consists of an array (instead of the associative array) so you might want to use the foreach to access each of those elements:
foreach ($tournaments as $update):
?>
<h3>Updates</h3>
<h1><?php echo $update ['Update']['title']; ?></h1>
<p><?php echo $update ['Update']['body']; ?></p>
<hr/>
<?php endforeach; ?>
It appears that you be using the wrong variable, you talk about the $updates variable but you're using the $tournament variable in your view.
<?php foreach ($updates['Update'] as $update): ?>
<h3>Updates</h3>
<h1><?php echo $update ['title']; ?></h1>
<p><?php echo $update ['body']; ?></p>
<hr/>
<?php endforeach; ?>
Additionally you haven't posted the whole controller method, which includes that find but you might not have sent the data to the view yet either
$this->set(compact('updates'));