I tried to create a pagination on my website using the bundle KnpPaginator.
In my repository I create a query :
public function getProductsOrderByDateDesc($id_category = null, $max = null){
$qb = $this->createQueryBuilder('p')
->orderBy('p.created_at', 'DESC');
if($max) {
$qb->setMaxResults($max);
}
if($id_category) {
if(is_array($id_category)){
$aIdCategory = implode("','",$id_category);
$qb->andWhere('p.category IN (:ids)')
->setParameter('ids', $aIdCategory);
}else{
$qb->andWhere('p.category = :category_id')
->setParameter('category_id', $id_category);
}
}
$query = $qb->getQuery();
return $query->getArrayResult();
}
In my controller I do :
$repositoryProduct = $em->getRepository('ShopDesktopBundle:Product');
$aProducts = array();
$aProducts = $repositoryProduct->getProductsOrderByDateDesc($id);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$aProducts,
$this->get('request')->query->get('page', 1),
3
);
return $this->render('ShopDesktopBundle:Category:category.html.twig',array(
'aProducts' => $aProducts,
'pagination' => $pagination
));
In view I only show this pagination :
<div class="navigation">
{{ knp_pagination_render(pagination) }}
</div>
The problem is that always displays all products not only the limit who for my example is 3.
For example :
I have 9 products, limit = 3, the pagination is correct "1 2 3" but for every page I see all 9 products
Help me please ! Thx in advance
Almost correct, however you have to use the pagination object instead of the 'aProducts'. In your view, use the following code:
{% for product in pagination %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
<td>{{ product.id }}</td>
<td>{{ product.title }}</td>
</tr>
{% endfor %}
See more info in the documentation, under 'View': https://github.com/KnpLabs/KnpPaginatorBundle
Related
I have been trying to figure out how I can pull the url of a node content type using an entity reference.
Apparently using {{ links.entity.uri }} or {{ links.entity.url }} does not work
<div>
{% for links in node.field_related_items %}
<h2>{{ links.entity.label }}</h2>
<a href="{{ links.entity.uri }} " ></a>
{% endfor %}
</div>
This worked for me:
This will only take you to /node/entity_id though and not /entity_name/entity_id
I would like to expand upon this answer by saying that you should add a Drupal::entityQuery() to your .theme file. Inside of this query, you'll want to grab the "alias" which is the link to the content. In your case this will give you these links /migrations and /aboutiom.
Here's an example of what that might look like...
function theme_name_preprocess_node(&$variables) {
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('type', 'related_links')
$nids = $query->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
$related_links = [];
foreach ($nodes as $item) {
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$item->id());
$related_links[] = [
'title' => $item->getTitle(),
'id' => $item->id(),
'field' => $item->get('field_name')->value,
'alias' => $alias,
];
}
$variables['related_links'] = $related_links;
}
Now in your twig template you can do something like this...
{% for link in related_links %}
{{ link['title'] }}
{% endfor %}
I've found the following code in Posts.php - I think I essentially need to duplicate this and turn it into a public function limiting the category to a sepcific ID. Although that seems overkill? Can I query the current function on the front end?
Here's the posts.php code:
protected function listPosts()
{
$category = $this->category ? $this->category->id : null;
/*
* List all the posts, eager load their categories
*/
$isPublished = !$this->checkEditor();
$posts = BlogPost::with('categories')->listFrontEnd([
'page' => $this->property('pageNumber'),
'sort' => $this->property('sortOrder'),
'perPage' => $this->property('postsPerPage'),
'search' => trim(input('search')),
'category' => $category,
'published' => $isPublished,
'exceptPost' => $this->property('exceptPost'),
]);
/*
* Add a "url" helper attribute for linking to each post and category
*/
$posts->each(function($post) {
$post->setUrl($this->postPage, $this->controller);
$post->categories->each(function($category) {
$category->setUrl($this->categoryPage, $this->controller);
});
});
return $posts;
}
on the front end is this:
{% for post in posts %}
<li>
<h3>{{ post.title }}</h3>
</li>
{% else %}
<li class="no-data">{{ noPostsMessage }}</li>
{% endfor %}
Could someone point me in the right direction?
Cheers,
Not sure what you want to achieve. You just want to show posts from specific category only?
Set the parameter "category filter" of your blogPosts component to the slug of specific category
[blogPosts newsList]
pageNumber = "{{ :page }}"
categoryFilter = "news"
postsPerPage = 100
noPostsMessage = "No posts found"
sortOrder = "published_at desc"
categoryPage = "blog/category"
postPage = "blog/post"
==
{% component 'newsList' %}
this will show posts only from "news" category
I have two tables in my database, form_settings and webmaster, that are on a one-to-many relationship, and this has been defined in their Models.
FormSettings.php
class FormSettings extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany('db_table', 'webmaster', 'db_table');
}
}
Webmaster.php
class FormSettings extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->belongsTo('db_table', 'form_settings', 'db_table');
}
}
In my Controller, I perform the following find() and pass it to the view:
ControllerBase.php
class ControllerBase extends Controller
{
public function initialize()
{
$exhibitions = FormSettings::find(
array(
'form_type = "v" AND show_end_date > NOW() AND archived = "n"',
'order' => 'db_table'
)
);
$this->view->exhibitions = $exhibitions;
}
}
And I know it's correctly linking rows from my webmaster table, as I have the following code in my View, and it displays webmaster_id values:
index.volt
{% for exhibition in exhibitions %}
<li>
{{ link_to('index/browse/' ~ exhibition.db_table, exhibition.db_table) }}
<!-- testing below -->
{% for webm in exhibition.webmaster %}
{{ webm.webmaster_id }}
{% endfor %}
<!-- end testing -->
</li>
{% endfor %}
My question is three-part:
How can I only link webmaster rows that have a column extra_1 as not NULL?
How can I count() the linked webmaster rows for each db_table (which is unique in form_settings)?
How can I pass this information through to the View in my $exhibitions object so that I can echo the count() in Volt syntax?
Hey and first of all thank you for the nice question formatting.
Excuse me for using examples that use my current database structure. But you can easily update your code.
1) You can set additional parameters to the relation definition.
$this->hasMany('id', 'Models\News', 'category_id', [
'alias' => 'news',
'reusable' => true,
'params' => [
'order' => 'id DESC',
'conditions' => 'extra_1 IS NOT NULL',
]
]);
Please note the reusable above. When using it, the query runs only once per request. Considering you want to count records and iterate over them its a nice performance boost.
2 + 3) Iterating over results in volt and counting:
Controller code:
$this->view->categories = \Models\NewsCategories::find();
Volt:
{% for category in categories %}
{% if category.news|length > 0 %} // Do not print categories without articles
<h3>Category #{{ category.id }} with total of {{ category.news|length }} articles.</h3>
<ul>
{% for item in category.news %}
<li>News #{{ item.id }}</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
The above code in my case produces the following output:
Category #4 with total of 4 articles.
News #3
News #4
News #5
News #7 Category #5 with total of 1 articles.
News #1
In Symfony2, how will i highlight the word i search from the search box :
// Search Twig:
{% block body -%}
<h1>Results of "{{ find }}"</h1>
{% if entities%}
{% for entity in entities %}
<table class="record_properties">
<tbody>
<tr>
<td>>{{ entity.question }}</td>
</tr>
</tbody>
</table>
{% endfor %}
{%else%}
<td>No Results found</td>
{%endif%}
{% endblock %}
//searchController :
public function searchAction() {
$request = $this->getRequest();
$data = $request->request->all();
$find = $data['search'];
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p.id, p.question
FROM EpitaEpitaBundle:questionanswer p
WHERE p.question LIKE :data')
->setParameter('data', "%$find%");
$res = $query->getResult();
return $this->render('EpitaEpitaBundle:questionanswer:search.html.twig', array(
'entities' => $res,
'find' => $find));
}
// I am getting the searched result but i want it to be highlighted...
You could, probably, do something like:
<td>>{{ entity.question|replace({find: "<span class='highlight'>" ~ find ~ "</span>"}) }}</td>
And then create a class in css:
span.hightlight {
/* Whatever you want to do with highlighted elements*/
}
Another option would be to write your own filter in PHP.
I'll suggest you to create your own filter as suggest by #Mindastic.
For that you will need a custom Twig extension, follow this cookbook entry to do that.
You will need to mark the output as safe HTML to make it work.
Last, but not least, for security reason, I encourage you to use PHP strip_tags() function on the input value to avoid injection.
So I am currently working on a project where I have a table that shows an overview of managers and the number of applications they are assigned to that currently have a certain status. What I am trying to do is when the user clicks on a number (which is the count) it returns a list view that queries from the database ONLY those applications that are assigned to that manager and that status. Otherwise, if the user goes to the application view, it should show ALL applications.
Here is the code of the View for my overview:
<table class="table tablesorter" id="tblAffs">
<thead>
<tr class="tblhead">
<th>AM</th>
<th>Qualified Prospect</th>
<th>Unqualified Prospect</th>
<th>Contacted</th>
<th>Converted To Account</th>
<th>Pending Integration</th>
<th>Revenue Generating</th>
</tr>
</thead>
<tbody>
#foreach ($totalCount as $id => $name) {{-- id is the admin id --}}
#foreach($name as $n => $status) {{-- $n is the name, $status is array of the counts --}}
<tr>
<td>
{{$n}}
<br>
Closed
</td>
<td>{{ isset($status[2]) ? $status[2] : 0 }}</td>
<td>{{ isset($status[1]) ? $status[1] : 0 }}</td>
<td>{{ isset($status[3]) ? $status[3] : 0 }}</td>
<td>{{ isset($status[4]) ? $status[4] : 0 }}</td>
<td>{{ isset($status[5]) ? $status[5] : 0 }}</td>
<td>{{ isset($status[6]) ? $status[6] : 0 }}</td>
</tr>
#endforeach
#endforeach
</tbody>
</table>
On my controller for this overview this is the code and how data structure created:
public function overview()
{
$query= DB::table('admins')
->join('advertiser_applications', 'admins.id', '=', 'advertiser_applications.assigned_to')
->selectRaw('advertiser_applications.status, admins.id, admins.first_name, COUNT(advertiser_applications.status) count')
->groupBy('admins.id', 'advertiser_applications.status');
$counts = $query->get();
$totalCount = [];
foreach($counts as $count){
$totalCount[$count->id][$count->first_name][$count->status] = $count->count;
}
return View::make('admin.crm.overview', ['totalCount' => $totalCount, 'admin_id' => AuthAdmin::admin(false), 'tpl_title' => 'CRM Advertiser Overview', 'new_lead' => 'advertisers']);
}
Here is the code from my Controller for my view that brings up the list. This is where I am confused as to how I will pass in that status and id if that href is clicked.
public function index($param)
{
$query = AdvertiserApplication::with('admin');
$status = Input::get('status');
if (!empty($status) || $status === '0')
$query->where('status', '=', $status);
$applications = $query->get();
return View::make('admin.advertisers.application_list', ['applications' => $applications, 'admin_id' => AuthAdmin::admin(false)]);
}
Now I am not sure if that is the proper way to link that I have written in my href. Should I do a URL link to route or something like that? I am not sure yet. Any tips would be much appreciated!
With this your URL:
{{ isset($status[2]) ? $status[2] : 0 }}
If you have
route::get('/ap1/{new_lead}', array('as' => 'page-name', 'uses' => 'yourController#functionName'));
in controller:
public function functionName($new_lead){
// use $new_lead here to get your data
}