Stuck for a second and for my solution did not find any answers, maybe i was searching wrong
My model
class MediaCategory extends Eloquent {
protected $table = "md_categories";
public function Media()
{
return $this->belongsToMany('Media', 'media_categories')->orderBy('id', 'DESC');
}
}
Controller
public function getCategory($slug)
{
$categories = $this->category->has('media')->orderBy('name', 'ASC')->get();
$medias = $this->category->whereSlug($slug)->get();
// $medias = $results->media();
$this->layout->title = 'Média tár';
$this->layout->content = View::make('front::page/results')
->with('categories', $categories)
->with('medias', $medias);
}
View
<div class="content-left">
#include('front::partials/search', array('categories' => $categories))
#foreach($medias as $data)
#foreach($data->media as $media)
<div class="gallery-thumbs">
<a class="view-more-image" href="{{ URL::to('media/details/'.$media->id) }}">Kép kiválasztása</a>
<a href="{{ URL::to($media->mediaOriginal()) }}" rel="prettyPhoto" title="{{ $media->title }}">
{{ HTML::image($media->mediaSmall()) }}
</a>
</div>
#endforeach
#endforeach
</div>
So when i change $medias = $this->category->whereSlug($slug)->get(); to $medias = $this->category->whereSlug($slug)->paginate(2ö); i only found sultions to the find() method
Could please someone give me a hint?
Okay, the result of not sleeping enough makes you ask stupid questions and results poor coding
Works fine, instead
$medias = $this->category->whereSlug($slug)->get();
Needed
$data = $this->category->whereSlug($slug)->first();
$medias = $data->media()->paginate(30);
Related
I have posts that, user can add comments to, but i unable to add those comments to that specific posts, here is the code that I'm following:-
the code is working fine with models and the only issue is when comment added, its added to only one post, rather than specific comment to specific post
HTML Code
<div class="quote-comment-box">
<form method="POST" class="com">
{% csrf_token %}
<input placeholder="Your thought" type="text" name="quote-comment" class="comment-input" id="{{ quote.id }}" title="{{ quote.user.id }}" data="{{ request.user }}">
<button type="submit" href="{% url 'micro__blog:quote_comment' %}" class="comment-button">POST</button>
</form>
<div class="content" id="content">
</div>
</div>
js code
$('.comment-button').click(function (params) {
csrftoken()
var index = $('.comment-button').index(this)
var comment = $( ".comment-input" ).eq(index).val()
var id = $( ".content" ).eq(index).attr('id')
params.preventDefault()
$.ajax({
url:$(this).attr("href"),
data:{
'blog_id' : $( '.comment-input' ).eq(index).attr('id'),
'blog_user' : $( '.comment-input' ).eq(index).attr('title'),
'comment' : $( ".comment-input" ).eq(index).val(),
},
type:'POST',
dataType: 'json',
success: function (res, status) {
if (res['status'] == 'ok') {
$('.comment-input').eq(index).val('');
var content = $('.content').eq(index)
console.log(index, content)
const div = document.createElement('div');
div.className = "comment-added"
div.innerHTML = `
<span class="user">` + $( ".comment-input" ).eq(index).attr('data') + `</span>
<span class="text">` + comment + `</span>`;
document.getElementById('content').appendChild(div);
console.log(res.status)
} else {
console.log(res.status)
}
},
error: function (res) {
console.log(res.status);
}
})
Here is view code
def quote_comment(request):
if request.method == 'POST':
blog_id = request.POST.get('blog_id')
blog_user = request.POST.get('blog_user')
comment = request.POST.get('comment')
current_user = User.objects.get(id = request.user.id)
if blog_id and blog_user and comment and current_user:
blog_id = Quote.objects.get(id = blog_id)
blog_user = User.objects.get(id=blog_user)
try:
QuoteComment.objects.get_or_create(user=current_user,blog_id=blog_id,blog_user_id=blog_user,comment=comment)
return JsonResponse({'status':'ok'})
except User.DoesNotExist:
return JsonResponse({'status':'error'})
return JsonResponse({'status':'error'})
and url
path('quote_comment/', views.quote_comment, name="quote_comment"),
A view that renders this template
def index(request):
quotes= Quote.objects.all()
return render(request=request, template_name="dashboard.html",context={'quotes':quotes})
to render on quotes im suing for loop like this
{% for quote in quotes %}
{% endfor %}
I have project where we need to create a live search with knockout, map with some titles, when the title enter in search field other titles should disappear, I try to use different code but non of them work, and there is no error to help me figure out.
my code for html :
Filter:
<ul data-bind="foreach: locations">
<li data-bind="text: title"></li>
</ul>
</div>
And for js:
function ViewModel(){
var self =this;
this.filter = ko.observable();
this.locations = ko.observableArray([{ title:'Safa Bridge'},{ title:'Holy Mosque'},{ title:'Diamond Tower'},{ title:'Albaik Resturant'},{ title:'Zamzam'}]);
this.visibleLocations = ko.computed(function(){
return this.locations().filter(function(location){
if(!self.filter() || location.title.toLowerCase().indexOf(self.filter().toLowerCase()) !== -1)
return location;
});
},this);
}
ko.applyBindings(new ViewModel());
I am converting an angular 2 component to use asynchronous data sources.
I had a <div class="col s4" *ngFor="let line of lines; let i = index;"> which worked when lines was an Array of Objects, however, lines is now an Observable of an Array of Objects.
This causes error:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
I tried <div class="col s4" *ngFor="let line of lines | async; let i = index;"> however, that didn't seem to make a difference.
How should I deal with this?
Here is an example binding to an observable array. It would be helpful if you posted your controller/component code too.
#Component({
selector: 'my-app',
template: `
<div>
<h2>Wikipedia Search</h2>
<input type="text" [formControl]="term"/>
<ul>
<li *ngFor="let item of items | async">{{item}}</li>
</ul>
</div>
`
})
export class App {
items: Observable<Array<string>>;
term = new FormControl();
constructor(private wikipediaService: WikipediaService) {
this.items = this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.wikipediaService.search(term));
}
}
http://blog.thoughtram.io/angular/2016/01/07/taking-advantage-of-observables-in-angular2-pt2.html
Using an array from Observable Object with ngFor and Async Pipe Angular 2
The answer to the question above is this:
// in the service
getItems(){
return Observable.interval(2200).map(i=> [{name: 'obj 1'},{name: 'obj 2'}])
}
// in the controller
Items: Observable<Array<any>>
ngOnInit() {
this.items = this._itemService.getItems();
}
// in template
<div *ngFor='let item of items | async'>
{{item.name}}
</div>
Hi I have implemented a search facility in laravel it returns the search query but I also get this error in my laravel log as follows:
[2014-09-14 21:06:20] production.ERROR: exception
'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method
Illuminate\Database\Eloquent\Collection::links()' in
/media/sf_Sites/tempus/app/storage/views/424d7d6280a6a7c59b31268a6d17e44a:27
Stack trace:
#0 [internal function]: Illuminate\Exception\Handler->handleShutdown()
#1 {main} [] []
My code is as follows:
Projects/Index
#extends('layouts.master')
#section("content")
<div class="container">
<div>
{{ Form::open(['method' => 'GET', 'class' => 'nav-bar-form navbar-right']) }}
<div class="form-group">
{{ Form::input('search', 'q', null,['class' => 'form-control','placeholder' => 'Search']) }}
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
<p> {{ $project->project_name }}</p>
#endforeach
#else
<h5 class="errorslist">No match found</a></h5>
#endif
#endif
</div>
<div class="container">
<ul class="pagination">
<li>{{ $projects->links() }}</li>
</ul>
</div>
{{ Form::close() }}
#stop
Repository
public function searchProjects($query){
return \Project::where('project_name', 'LIKE', "%$query%" )
->orderby('project_name', 'asc')
->get();
}
public function getAll()
{
// get all logged in users projects and paginate 9 per page
return \Auth::user()->projects()->orderBy('project_name', 'asc')->paginate(9);
}
Controller:
public function index()
{
$query = Request::get('q');
$projects = $query
? $this->project->searchProjects($query)
: $this->project->getAll();
echo View::make('projects.index', compact('projects'));
}
Routes
Route::get('projects/index', array('before' => 'auth',
"as" => "projects/index",
"uses" => "ProjectController#index"
));
I'm not sure why I'm getting an error when I perform a search query on my links method, any ideas?
You need paginate on your searchProjects method as well:
public function searchProjects($query){
return \Project::where('project_name', 'LIKE', "%$query%" )
->orderby('project_name', 'asc')
->paginate(9);
}
I want to create a searchController, that searches the db for whatever keywords the user enters into a textbox. I have looked at this article and this and many more.
This is what I have so far:
public function searchAction(Request $request) {
if ($request->getMEthod() == 'GET') {
$title = $request->get('Search_term');
//echo "<div class=\"searchText\">Search Results</div><hr/>";
$em = $this->getDoctrine()->getManager();
$Search_terms = explode(' ', $title); //splits search terms at spaces
$query = "SELECT * FROM Entity/Adverts WHERE ";
foreach ($Search_terms as $each) {
// echo $each."<br/>";
$i = 0;
$i++;
if ($i == 1)
$query .= "Adv_title LIKE '%$each%' ";
else
$query .= "OR Adv_title LIKE '%$each%' ";
}
$query = $em->createQuery($query);
$numRow = $query->count();
if ($numRow > 0) {
while ($query->fetch()) {
$repository = $em->getRepository('YCRYcrBundle:Adverts')->findBy(array(
'advTitle' => $title
));
/* echo "<h2><a href='#'> $title</a> </h2>";
echo "$desc <br /> <br />";
echo"<a href='/201308/View/YCR/index.php' class='link-button right'><span>Apply</span></a>"; */
}
}
/* else
echo "none found for \"<b>$SearchTerm </b>\"</br>Check spelling"; */
}
return $this->render('YCRYcrBundle:Search:search.html.twig', array('title' => $title->getAdvTitle()));
}
What is missing from this code to make it work, and or what is wrong?
Edit:
sorry of I was unclear. I am getting the following error:
FatalErrorException: Error: Call to undefined method Doctrine\ORM\Query::count() in C:\wamp\www\201308\src\YCR\YcrBundle\Controller\SearchController.php line 28
and do not know what is wrong as I am new to Symfony and doctrine.
This is what I have in my search.html.twig:
{% extends "YCRYcrBundle::layout.html.twig" %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>YCR Job Search</title>
<link href="stylesheets/style.css" rel="stylesheet" type="text/css" />
<link href="stylesheets/colour.css" rel="stylesheet" type="text/css" />
</head>
<body onload="b = setInterval('clear()', 0);">
<div class="topDiv">
<div style="float: left;">
<img src="/201308/View/images/ycr.jpg" alt="ycr"></div>
<br/>
<!--<H2>Search for a Job</H2>-->
<div class="searchform">
<form id="formsearch" name="p" method="get" action="index.php">
<span>
<input name="Search_term" class="editbox_search" id="editbox_search" maxlength="80" value="<?php $this; ?>" type="text" />
</span>
<input type="image" name="button_search" src="images/search.gif" class="button_search" alt="" />
</form>
<br/>
<div id="search_results">
</div>
</div>
<!-- </div>-->
<script type="text/javascript" src="http://code.jquery.com/jquery- 1.7.2.min.js"></script><!--javascript jquery library-->
<script type="text/javascript" src="../View/scripts/Script.js"></script>
{% endblock %}
When the user searches, for example programmer, to display like this:
-Programmer
-a summary of the description of what a programmer entails
-a button/link that reads: read more, that takes me to a page with full description
You are pretty far off the mark. Query has no count function, that's a querybuilder function. You may write raw sql, but you are better served learning querybuilder : http://docs.doctrine-project.org/en/latest/reference/query-builder.html. Remember, doctrine is designed to give you a list of entities, that you pass to the twig to do stuff with.
Also, your twig won't do much, see the basics of usage in the very crude twig I've included. use {{entity.method}} or {{entity.field}} to get the various display properties of each entity. Use a twig foreach to loop through them all. Take a look at my example in your context, and then go read the twig documents to fill in the gaps. http://twig.sensiolabs.org/documentation
The Controller
public function searchAction(Request $request) {
if ($request->getMethod() == 'GET') {
$title = $request->get('Search_term');
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository('YCRYcrBundle:Adverts')
->createQueryBuilder('a');
$searches= explode(' ', $title);
foreach ($searches as $sk => $sv) {
$cqb[]=$qb->expr()->like("CONCAT($sv, '')", "'%$sv%'");
}
$qb->andWhere(call_user_func_array(array($qb->expr(),"orx"),$cqb));
$adverts = $qb->getResult();
}
return $this->render('YCRYcrBundle:Search:search.html.twig'
, array('adverts' => $adverts));
}
And a twig file
{# Your other stuff #}
{% for advert in adverts %}
{{advert.getId}}
{# call the various method and fields for your display#}
{% endfor %}
you need to execute the query (with execute ) or you wont get an array. and you should be using the query builder instead DQL string concatenation. Read the doctrine doc on basic doctrine usage , the entity namespace seems to be incorrect too.
i quote you :
$query = $em->createQuery($query);
$numRow = $query->count();
should be at least :
$query = $em->createQuery($query);
$numRow = count($query->execute())
edit : not sure wether you would be getting an array or an ArrayCollection , check if the count fonction works on the ArrayCollection.