This is Cakephp 3.5, So I have three businesses 1, 2, 3. I have a view to show Estimated Revenue From Fees.
On the index page I have a three column Div
<div class="row">
<div class="col-md-12">
<h2><?= __('Estimated Revenue From Fees') ?></h2>
<div class="row">
<div class="column">
<h4>Business One</h4>
<ul>
<?php foreach ($estimatedRevenueFromCFeesBiz1 as $estimatedRevenueFromFeeBiz1): ?>
<li class="actions">
<?= $this->Html->link(__( h($estimatedRevenueFromFeeBiz1->year), ['action' => 'view', $estimatedRevenueFromFeeBiz1->id]) ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="column">
<h4>Business Two</h4>
<?php foreach ($estimatedRevenueFromFeesNauBiz2 as $estimatedRevenueFromFeeBiz2): ?>
<li class="actions">
<?= $this->Html->link(__( h($estimatedRevenueFromFeeNauBiz2->year), ['action' => 'view', $estimatedRevenueFromFeeBiz2->id]) ?>
</li>
<?php endforeach; ?>
</div>
<div class="column">
<h4>Business Three</h4>
<?php foreach ($estimatedRevenueFromCourseFeesUa as $estimatedRevenueFromCourseFeeUa): ?>
<li class="actions">
<?= $this->Html->link(__( h($estimatedRevenueFromFeeBiz3->year), ['action' => 'view', $estimatedRevenueFromFeeBiz3->id]) ?>
</li>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
In my controller I've set up like this:
public function index()
{
$estimatedRevenueFromFeesBiz1 = $this->EstimatedRevenueFromFeesBiz1->find('list', array( 'conditions' => 'business_id' == 1));
$estimatedRevenueFromFeesBiz2 = $this->EstimatedRevenueFromFeesBiz2->find('list', array( 'conditions' => 'business_id' == 2));
$estimatedRevenueFeesBiz3 = $this->EstimatedRevenueFromFeesBiz3->find('list', array( 'conditions' => 'business_id' == 1));
$this->set(compact('estimatedRevenueFromFeesBiz1', 'estimatedRevenueFromFeesBiz2', 'estimatedRevenueFromFeesBiz3'));
}
I'm getting a Call to a member function find() on boolean
Error in: ROOT\src\Controller\EstimatedRevenueFromCourseFeesController.php, line 26 which is the
$estimatedRevenueFromFeesBiz1 = $this->EstimatedRevenueFromFeesBiz1->find('list', array( 'conditions' => 'business_id' == 1)); line.
I figured it out. I changed the controller back to just calling the whole table:
public function index()
{
$this->paginate = [
'contain' => ['Businesses']
];
$estimatedRevenueFromFees = $this->paginate($this->EstimatedRevenueFromFees);
$this->set(compact('estimatedRevenueFromFees'));
}
I then added a condition into the index.ctp file:
<h4>Business One</h4>
<ul>
<?php foreach ($estimatedRevenueFromFees as $estimatedRevenueFromFee): ?>
<?php if ($estimatedRevenueFromFee['business_id'] == 1): ?>
<li class="actions">
<?= $this->Html->link(__( h($estimatedRevenueFromFee->year), ['action' => 'view', $estimatedRevenueFromFee->id]) ?>
</li>
<?php else: ?>
<?php continue; ?>
<?php endif; ?>
<?php endforeach; ?>
</ul>
Well, based on what you said and on your own answer, it looks like what you were trying to do was this:
public function index() {
$estimatedRevenueFromFeesBiz1 = $this->EstimatedRevenueFromFees->find('list', ['conditions' => ['business_id' == 1]]);
$estimatedRevenueFromFeesBiz2 = $this->EstimatedRevenueFromFees->find('list', ['conditions' => ['business_id' == 2]]);
$estimatedRevenueFeesBiz3 = $this->EstimatedRevenueFromFees->find('list', ['conditions' => ['business_id' == 1]]);
$this->set(compact('estimatedRevenueFromFeesBiz1', 'estimatedRevenueFromFeesBiz2', 'estimatedRevenueFromFeesBiz3'));
}
What changes is your condition (business_id). But you are always querying over the same table (EstimatedRevenueFromFees).
Bare in mind that in your solution you are paginating. So you might end up having every record in a page with a certain business_id, or whatever combination.
Related
I'm new on CakePHP and I need to develop a system where the user log in and post a comment, but I don't know how can I get his id and insert in user_id FK from 'comments'. Can someone help me?
add function - ComentarioController.php:
public function add()
{
$comentario = $this->Comentario->newEntity();
if ($this->request->is('post')) {
$comentario = $this->Comentario->patchEntity($comentario, $this->request->data);
if ($this->Comentario->save($comentario)) {
$this->Flash->success(__('Comentário enviado com sucesso'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Erro no envio do comentário'));
}
}
$this->set(compact('comentario'));
$this->set('_serialize', ['comentario']);
}
add.ctp:
<nav class="large-3 medium-4 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('Listar Comentarios'), ['action' => 'index']) ?></li>
</ul>
</nav>
<div class="comentario form large-9 medium-8 columns content">
<?= $this->Form->create($comentario) ?>
<fieldset>
<legend><?= __('Postar Comentario') ?></legend>
<?php
echo $this->Form->input('comentario');
?>
</fieldset>
<?= $this->Form->button(__('Comentar')) ?>
<?= $this->Form->end() ?>
</div>
If the user is already logged in you can get his id with$this->Auth->user() or AuthComponent::user()
If you have no login System yet try the CakeDC/Users plugin, this should normally work out of the box and helped me a lot of times.
Yii Version 1.1.15
I have a model which contains a serialized array (table) in an attribut. Showing this array as a table in a view works fine.
But I want to update the table-cells and then again save the array serialized in the model. And this does not work. The output stops there (*) without errors.
Here you can see what I did:
$model->table contains a serialized array. The unserialized array looks like this:
array(
array('dog', 'cat', 'cow'),
array('meat', 'milk', 'gras'),
)
I unserialize the table in the controller:
controller: contactController.php
$model = Contact::model()->findByPk((int) $id);
$table = unserialize($model->input)
$this->render('contact_form', array(
'table' => $table));
}
And now I want to show and edit the array $table in a form as a html-table:
view: contact_form.php
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'contact-form',
));
?>
<table border="2">
<?php foreach ($table as $row): ?>
<tr>
<?php foreach ($row as $value): ?>
<td>
<!-- (*) output stops here, without errors -->
<?= $form->textArea($value, '', array('rows' => 3, 'cols' => 20)); ?>
</td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
<div class="row buttons">
<?php echo CHtml::submitButton("save"); ?>
</div>
<?php $this->endWidget(); ?>
The output stops before "... textArea ...".
If I only show $table in a view (without a form) it works like a charme:
<table border="2">
<?php foreach ($table as $row): ?>
<tr>
<?php foreach ($row as $value): ?>
<td><?= CHtml::encode($value) ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
Hope this helps to help me :-) How can I get this nice idea working?
Actually you are missing the arguments of CactiveForm.textArea(.......)
http://www.yiiframework.com/doc/api/1.1/CActiveForm#textArea-detail
textArea($value, '', array('rows' => 3, 'cols' => 20)); ?>
Instead of it your code should be
textArea($model, $value, array('rows' => 3, 'cols' => 20)); ?>
Need some help getting widget to sort the reviews from low to high. I know this is reverse of the norm, but this website focuses on how "bad" something is. The website is here: http://designtatics.fatcow.com/Badkickstarter/ it's the second tab down called top 3. Excuse the mess, still a work in progress.
// order by rating?
if (isset($order) && $order == 'rating') {
$query_args['orderby'] = 'meta_value';
}
else {
$query_args['orderby'] = 'date';
}
$r = new WP_Query($query_args);
I've already tried adding $query_args['order'] = 'ASC'; with no luck. This is all new to me so the more specific the better. Thanks!
UPDATE: I think I was trying to modify the wrong widget, heres the new code:
<?php
class Bunyad_TabbedRecent_Widget extends WP_Widget
{
public function __construct()
{
parent::__construct(
'bunyad-tabbed-recent-widget',
'Bunyad - Recent Tabs',
array('description' => __('Tabs: Recent, category1, category2...', 'bunyad-widgets'), 'classname' => 'tabbed')
);
add_action('save_post', array($this, 'flush_widget_cache'));
add_action('deleted_post', array($this, 'flush_widget_cache'));
add_action('switch_theme', array($this, 'flush_widget_cache'));
// init hook
add_action('init', array($this, 'init'));
}
public function init()
{
// only in admin cp for form
if (is_admin()) {
wp_enqueue_script('widget-tabs', plugins_url('/bunyad-widgets/js/widget-tabs.js'));
}
}
// #todo wrap existing widgets with in-memory cache
public function widget($args, $instance)
{
global $post; // setup_postdata not enough
// set defaults
$titles = $cats = $tax_tags = array();
extract($args);
extract($instance);
// missing data?
if (!count($titles) OR !count($cats)) {
_e('Recent tabs widget still need to be configured! Add tabs, add a title, and select type for each tab in widgets area.', 'bunyad-widgets');
return;
}
$tabs = array();
foreach ($titles as $key => $title) {
// defaults missing?
if (empty($tax_tags[$key])) {
$tax_tags[$key] = '';
}
if (empty($cats[$key])) {
$cats[$key] = '';
}
$tabs[$title] = array('cat_type' => $cats[$key], 'tag' => $tax_tags[$key]);
}
// latest posts
$posts = $this->get_posts($tabs, $number);
?>
<?php echo $before_widget; ?>
<ul class="tabs-list">
<?php
$count = 0;
foreach ($posts as $key => $val): $count++; $active = ($count == 1 ? 'active' : '');
?>
<li class="<?php echo $active;?>">
<?php echo $key; ?>
</li>
<?php endforeach; ?>
</ul>
<div class="tabs-data">
<?php
$i = 0;
foreach ($posts as $tab => $tab_posts): $i++; $active = ($i == 1 ? 'active' : ''); ?>
<ul class="tab-posts <?php echo $active; ?> posts-list" id="recent-tab-<?php echo esc_attr($i); ?>">
<?php if ($tabs[$tab] == 'comments'): ?>
<?php
foreach ($tab_posts as $comment):
?>
<li class="comment">
<span class="author"><?php printf('%s said', get_comment_author_link($comment->comment_ID)); ?></span>
<p class="text"><?php comment_excerpt($comment->comment_ID); ?></p>
<?php echo get_the_title($comment->comment_post_ID); ?>
</li>
<?php
endforeach;
?>
<?php else: ?>
<?php foreach ($tab_posts as $post): setup_postdata($post); ?>
<li>
<a href="<?php the_permalink() ?>"><?php the_post_thumbnail('post-thumbnail', array('title' => strip_tags(get_the_title()))); ?>
<?php if (class_exists('Bunyad') && Bunyad::options()->review_show_widgets): ?>
<?php echo apply_filters('bunyad_review_main_snippet', ''); ?>
<?php endif; ?>
</a>
<div class="content">
<time datetime="<?php echo get_the_date('Y-m-d\TH:i:sP'); ?>"><?php echo get_the_date(); ?> </time>
<span class="comments"><a href="<?php echo esc_attr(get_comments_link()); ?>"><i class="fa fa-comments-o"></i>
<?php echo get_comments_number(); ?></a></span>
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr(get_the_title() ? get_the_title() : get_the_ID()); ?>">
<?php if (get_the_title()) the_title(); else the_ID(); ?></a>
</div>
</li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
<?php endforeach; ?>
</div>
<?php echo $after_widget; ?>
<?php
wp_reset_postdata();
}
public function get_posts($tabs, $number)
{
// posts available in cache? - use instance id to suffix
$cache = get_transient('bunyad_tabbed_recent_posts');
if (is_array($cache) && isset($cache[$this->number])) {
return $cache[$this->number];
}
// get posts
$args = array('numberposts' => $number, 'ignore_sticky_posts' => 1);
foreach ($tabs as $key => $val) {
$opts = array();
switch ($val['cat_type']) {
case 'popular':
$opts['orderby'] = 'comment_count';
break;
case 'comments':
$posts[$key] = get_comments(array('number'=> $number, 'status' => 'approve'));
continue 2; // jump switch and foreach loop
case 'top-reviews':
// get top rated of all time
$opts = array_merge($opts, array('orderby' => 'meta_value', 'meta_key' => '_bunyad_review_overall'));
break;
case 'recent':
break;
case 'tag':
$opts['tag'] = $val['tag'];
break;
default:
$opts['cat'] = intval($val['cat_type']);
break;
}
//$query = new WP_Query(array_merge($args, $opts));
$posts[$key] = get_posts(array_merge($args, $opts));
}
if (!is_array($cache)) {
$cache = array();
}
$cache[ $this->number ] = $posts;
set_transient('bunyad_tabbed_recent_posts', $cache, 60*60*24*30); // 30 days transient cache
return $posts;
}
public function flush_widget_cache()
{
delete_transient('bunyad_tabbed_recent_posts');
}
public function update($new, $old)
{
// fix categories
foreach ($new['cats'] as $key => $cat) {
$new['cats'][$key] = strip_tags($cat);
}
foreach ($new['titles'] as $key => $title) {
$new['titles'][$key] = strip_tags($title);
}
foreach ($new['tax_tags'] as $key => $tag) {
$new['tax_tags'][$key] = trim(strip_tags($tag));
}
$new['number'] = intval($new['number']);
// delete cache
$this->flush_widget_cache();
return $new;
}
public function form($instance)
{
$instance = array_merge(array('titles' => array(), 'cats' => array(0), 'number' => 4, 'cat' => 0, 'tax_tags' => array()), $instance);
extract($instance);
?>
<style>
.widget-content p.separator { padding-top: 10px; border-top: 1px solid #d8d8d8; }
.widget-content .tax_tag { display: none; }
</style>
<div id="tab-options">
<script type="text/html" class="template-tab-options">
<p class="title separator">
<label><?php printf(__('Tab #%s Title:', 'bunyad-widgets'), '<span>%n%</span>'); ?></label>
<input class="widefat" name="<?php
echo esc_attr($this->get_field_name('titles')); ?>[%n%]" type="text" value="%title%" />
</p>
<div class="cat">
<label><?php printf(__('Tab #%s Category:', 'bunyad-widgets'), '<span>%n%</span>'); ?></label>
<?php
$r = array('orderby' => 'name', 'hierarchical' => 1, 'selected' => $cat, 'show_count' => 0);
// categories list
$cats_list = walk_category_dropdown_tree(get_terms('category', $r), 0, $r);
// custom options
$options = array(
'recent' => __('Recent Posts', 'bunyad-widgets'),
'popular' => __('Popular Posts', 'bunyad-widgets'),
'top-reviews' => __('Top Reviews', 'bunyad-widgets'),
'tag' => __('Use a Tag', 'bunyad-widgets'),
);
?>
<select name="<?php echo $this->get_field_name('cats') .'[%n%]'; ?>">
<?php foreach ($options as $key => $val): ?>
<option value="<?php echo esc_attr($key); ?>"<?php echo ($cat == $key ? ' selected' : ''); ?>><?php echo esc_html($val); ?></option>
<?php endforeach; ?>
<optgroup label="<?php _e('Category', 'bunyad-widgets'); ?>">
<?php echo $cats_list; ?>
</optgroup>
</select>
<div class="tax_tag">
<p><label><?php printf(__('Tab #%s Tag:', 'bunyad-widgets'), '<span>%n%</span>'); ?></label> <input type="text" name="<?php
echo esc_attr($this->get_field_name('tax_tags')); ?>[%n%]" value="%tax_tag%" /></p>
</div>
<p>[x] <?php _e('remove', 'bunyad-widgets'); ?></p>
</div>
</script>
<p class="separator"><?php _e('Add More Tabs', 'bunyad-widgets'); ?></p>
<?php
if (is_integer($this->number)): // create for valid instances only
foreach ($cats as $n => $cat):
?>
<script>
jQuery(function($) {
$('.widget-liquid-right [id$="bunyad-tabbed-recent-widget-'+ <?php echo $this->number; ?> +'"] #add-more-tabs').trigger(
'click',
[{
'n': <?php echo ($n+1); ?>,
'title': '<?php echo esc_attr($titles[$n]); ?>',
'selected': '<?php echo esc_attr($cat); ?>',
'tax_tag': '<?php echo esc_attr($tax_tags[$n]); ?>'
}]);
});
</script>
<?php
endforeach;
endif;
?>
</div>
<p><label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of posts in each tab:', 'bunyad-widgets'); ?></label>
<input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" />
</p>
<?php
}
}
I am using cakephp 2.4
in my apps I have a view in CategoriesController namely "Editorial" and I can show all the articles under that category by http://mydomain/categories/editorial
I am trying to show all the articles under "Editorial" category in the home.ctp by echo $this->element('editorials');
but it shows Notice (8): Undefined variable: articles [APP\View\Elements\Editorials.ctp, line 4]
CategoriesController.php
public function Editorial() {
$category = $this->Category->find('first', array(
'conditions' => array(
'Category.id' => 1
)
));
$this->set(compact('category'));
$this->Paginator = $this->Components->load('Paginator');
$this->Paginator->settings = array(
'Article' => array(
'recursive' => -1,
'contain' => array(
'Category'
),
'limit' => 5,
'conditions' => array(
'Article.category_id' => $category['Category']['id'],
),
'order' => array(
'Article.id' => 'ASC'
),
'paramType' => 'querystring',
)
);
$articles = $this->Paginator->paginate($this->Category->Article);
$this->set(compact('articles'));
}
View file:
<?php if (!empty($articles)): ?>
<?php echo $this->element('editorials'); ?>
<?php echo $this->element('pagination-counter'); ?>
<?php echo $this->element('pagination'); ?>
<?php endif; ?>
Elements/Editorials.ctp:
<div class="row">
<?php
$i = 0;
foreach ($articles as $art):
$i++;
if (($i % 4) == 0) { echo "\n<div class=\"row\">\n\n";}
?>
<div class="col col-sm-3">
<?php echo $this->Html->link($art['Article']['title'], array('controller' => 'articles', 'action' => 'view', 'id' => $art['Article']['id'])); ?>
<br />
</div>
<?php
if (($i % 4) == 0) { echo "\n</div>\n\n";}
endforeach;
?>
<br />
<br />
</div>
try to add $this->render('file'); in your Editorial action and replace file with view file name without.ctp
Something you can change:
1. In controller:
$this->set(compact('category', 'articles')); // one set()
2. In view: (Main Point)
<?php echo $this->element('editorials', array('articles' => $articles)); ?>
Here, you need to pass the articles variable to element like above, by default an element don't recognize the viewVars.
I have a project in CakePHP application and I want to add pagination to it. I have added pagination to it, but when I click on a page number or go to the next page my application breaks.
The page relies on variables being passed to the controller in order to display the correct data. Here is my code for the view:
<table class="table table-striped">
<thead>
<tr>
<th>Job ID</th>
<th>Date</th>
<th>Site</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $jobsheet) { ?>
<tr>
<td>
<?php echo $jobsheet['Jobsheet']['jobnum']; ?>
</td>
<td>
<?php echo date("l, jS F Y", strtotime($jobsheet['Jobsheet']['jobdate'])); ?>
</td>
<td>
<span class="companyname"><strong><?php echo $jobsheet['Siteaddress']['sitename'] ?></strong></span><br />
<?php echo $jobsheet['Siteaddress']['addressline1']; ?>,
<?php echo $jobsheet['Siteaddress']['addressline2']; ?>,
<?php if ( $jobsheet['Siteaddress']['addressline3'] = '') { ?>
<?php echo $jobsheet['Siteaddress']['addressline3']; ?>,
<?php } else { ?>
<?php } ?>
<?php echo $jobsheet['Siteaddress']['city']; ?>,
<?php echo $jobsheet['Siteaddress']['county']; ?>,
<?php echo $jobsheet['Siteaddress']['country']; ?>,
<?php echo $jobsheet['Siteaddress']['postcode']; ?>
</td>
<td><a data-toggle="modal" href="#viewjobsheet<?php echo $jobsheet['Jobsheet']['id']; ?>" onClick="document.getElementById('jbif<?php echo $jobsheet['Jobsheet']['id']; ?>').src='/modal/customers/<?php echo $company['Company']['id']; ?>/jobs/<?php echo $jobsheet['Jobsheet']['id']; ?>/view/';" title="View" class="icon-eye-open"></a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="controls">
<?php echo $this->Paginator->prev('« Previous', null, null, array('class' => 'disabled')); ?>
<?php echo $this->Paginator->numbers(); ?>
<?php echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled')); ?>
<br />
<br />
<?php echo $this->Paginator->counter(array(
'format' => 'Page {:page} of {:pages}, showing {:current} records out of
{:count} total, starting on record {:start}, ending on {:end}'
));
?>
</div>
</div>
This is the controller:
function index(){
$companyid = $this->params['customer'];
$this->set('companyid', $companyid);
$siteid = $this->params['site'];
$this->loadModel('Jobsheet');
// Job Sheets
$jobsheets = $this->Jobsheet->find('all', array('conditions' => array('Jobsheet.company' => $companyid), 'recursive' => 2, 'order' => 'Jobsheet.jobdate DESC', 'limit' => '10'));
$this->set('jobsheets', $jobsheets);
$this->paginate = array(
'limit' => 10
);
$data = $this->paginate('Jobsheet');
$this->set(compact('data'));
}
While the pagination does work, it ends up loosing the variable and this breaks what I'm trying to do. What am i missing?
One method is to use PaginatorHelper::options (see the API)
For example, say we want to pass the variable $pass between Paginator page changes. So first pass the variable to the View.
public function index() {
$pass = 'testString';
$this->set(compact('pass'));
$this->set('posts', $this->paginate());
}
In the View, we can then add this to the parameters that Paginator passes when changing pages using Paginator::options and the url option.
<?php
$this->Paginator->options(array(
'url' => array(
'pass' => $pass
)
));
?>
So if you moved from page 1 to page 2, the resulting url would be something similar to:
http://localhost/cake/posts/index/pass:testString/page:2
This is also how Paginator passes sort orders and sort keys. So while "pass" in pass:testString can be anything you want, be sure not to use sort, direction, and page.
As long as you are changing pages through the Paginator links, the passed variables will remain. Note that you can access the values of the passed arguments in both the View and the Controller by the property:
$this->passedArgs