laravel search paginate Call to undefined method links() - search

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);
}

Related

if statement handlebars with passed 2 values

I'm making a site with handlebars and nodejs and I want to show a "message" (you can best compare them to tweets) only if the "message" is from a specific user.
For the if statement I used the following question asked on stackoverflow in the past: Logical operator in a handlebars.js {{#if}} conditional I'm passing through 2 variables: messages and username where username is a string and messages an array. I use message as |item| to get a specific place from the array. The username is stored in item.[0]. As I change the username in the value to "test" in line 3 of the hbs code so it would be {{#ifCond item.[0] "test"}} then it works, but not with the username passed through with the value.
Here's my handlebars code:
{{#if user}}
{{#each messages as |item|}}
{{#ifCond item.[0] username}}
<div class="card" style="width: 100%;">
<div class="card-body">
<h5 class="cardtitle">{{#key}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{item.[0]}}</h6>
<h6 class="card-subtitle mb-2 text-muted">{{item.[2]}}</h6>
<p class="card-text">{{item.[1]}}</p>
</div>
</div>
<p></p>
{{else}}
<p>{{item.[0]}}</p>
{{/ifCond}}
{{/each}}
{{/if}}
The node.js code to load the page:
router.get('/users',loggedIn,messages,(req, res) => {
var user = res.user
var username = req.query.user
var message = res.message
if (user != undefined){
res.render("publicprofile", {user:user, username:username, messages:message, usernamestr:String(username)})
} else{
res.redirect("/")
}
});
and the handlebars helper:
hbs.registerHelper('ifCond', function(v1, v2, options) {
if(v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});

how to add specific comment to post in django post

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 %}

Blaze LoginButtons Template Rendered in React - Login Only Works on Homepage

So I am using Meteor/React, but I used Blaze's login template for its convenience. It works great on the homepage, but when I try to login from any other page on the site, the page reloads and the login appears to have been unsuccessful.
This is my implementation.
AccountsUI.jsx
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
export class AccountsUI extends React.Component {
componentDidMount(){
this.view = Blaze.render(Template.loginButtons, this.refs.loginContainer);
}
componentWillUnmount(){
Blaze.remove(this.view);
}
render(){
return(
<span ref="loginContainer" />
)
}
}
mainLayout.jsx
<div className="container-fluid">
<a className="navbar-btn pull-left panel-body"><b>FAQ</b></a>
<a className="navbar-btn pull-right panel-body"><b>Category</b></a>
<a className="navbar-btn pull-right panel-body"><b>Notifications</b></a>
<a className="navbar-btn pull-right panel-body"><b><AccountsUI /></b></a>
</div>
</div>
Why would this work only on certain pages?
Blaze
Your code looks ok, are you importing all components correctly?
Try: https://atmospherejs.com/gadicc/blaze-react-component
and do:
import Blaze from 'meteor/gadicc:blaze-react-component';
....
<a className="navbar-btn pull-right panel-body"><b><Blaze template="loginButtons" /></b></a>
....
Without trying to change your choice of tools too much, I have been exploring React, Meteor and Authentication for a little while, often getting stuck in state management and other dark holes. Below is a overview of some options:
React Accounts-UI package
Personally as a quick tool I am a big fan of the React Accounts-UI package https://atmospherejs.com/std/accounts-ui
It's easy to implement and has many React specific config options.
Check out 'Create your own styled version' to implement in Navbar at https://github.com/studiointeract/accounts-ui/blob/master/README.md
React with Kadira FlowRouter and ReactLayout
For something within the Navbar, here is a stab with flow router.
From the Meteor Guide User/Authentication section:
While a router is optional and the basic functionality will work without it, it’s also a good idea to pick a router integration:
For Navbar login (Not React Accounts-UI).
You need Flowrouter and Reactlayout
Routes
We create 2 route groups which allow us to build auth logic into Flow router easily:
const publicRoutes = FlowRouter.group( { name: 'public' } );
publicRoutes.route( '/login', {
name: 'login',
action() {
ReactLayout.render( App, {
yield: <Login /> }
);
}
}
);
const authenticatedRoutes = FlowRouter.group( { name: 'authenticated' } );
authenticatedRoutes.route( '/hidden', {
name: 'hidden',
action() {
ReactLayout.render( App, {
yield: <Hidden /> }
);
}
}
);
App:
You can modify this to suit your own setup. The approach here is to grab the reactmeteordata mixing which allows us to test if the user is logged or logging in. The isPublic function allows us to test if the user should be allowed on the current route. The rest should be self explanatory.
App = React.createClass({
mixins: [ ReactMeteorData ],
getMeteorData() {
return {
loggingIn: Meteor.loggingIn(),
hasUser: !!Meteor.user(),
isPublic( route ) {
let publicRoutes = [
'login'
];
return publicRoutes.indexOf( route ) > -1;
},
canView() {
return this.isPublic( FlowRouter.current().route.name ) || !!Meteor.user();
}
};
},
loading() {
return <div className="loading"></div>;
},
getView() {
return this.data.canView() ? this.props.yield : <Login />;
},
render() {
return <div className="app-root">
<AppHeader hasUser={this.data.hasUser} />
<div className="container">
{this.data.loggingIn ? this.loading() : this.getView()}
</div>
</div>;
}
}
);
Header:
Nothing cosmic, we change the brandLink depending on user state. We then check hasUser (passed as a prop from the App component) to change which nav component to display.
AppHeader = React.createClass({
mixins: [ ReactMeteorData ],
getMeteorData() {
return { brandLink: !!Meteor.user() ? '/hidden' : '/login' }; },
render() {
return ( <nav className="navbar navbar-default" role="navigation">
<div className="container">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"><span className="sr-only">Toggle navigation</span><span className="icon-bar"></span> <span className="icon-bar"></span><span className="icon-bar"></span>
</button>
<a className="navbar-brand" href={this.data.brandLink}>AuthExample</a>
</div>
{this.props.hasUser ? <AuthenticatedNavigation /> : <PublicNavigation />}
</div>
</nav> );
}
});
AuthenticatedNavigation component :
AuthenticatedNavigation = React.createClass({
currentUserEmail() {
return Meteor.user().emails[0].address;
},
logout( event ) {
event.preventDefault();
return Meteor.logout( () =>
FlowRouter.go( '/login' ) );
},
render() {
return <div id="navbar-collapse" className="collapse navbar-collapse">
<ul className="nav navbar-nav">
<li className={FlowHelpers.currentRoute( 'hidden' )}>Hidden
</li>
</ul>
<ul className="nav navbar-nav navbar-right">
<li className="dropdown">
<a href="#" className="user-profile-toggle dropdown-toggle clearfix" data-toggle="dropdown">{this.currentUserEmail()} <span className="caret"></span>
</a>
<ul className="dropdown-menu" role="menu">
<li>Account Preferences</li>
<li className="logout" onClick={this.logout}>Logout</li>
</ul>
</li>
</ul>
</div>;
}
});
PublicNavigation Component:
PublicNavigation = React.createClass({
render() {
return (
<div id="navbar-collapse" className="collapse navbar-collapse">
<ul className="nav navbar-nav navbar-right">
<li className={FlowHelpers.currentRoute( 'login' )}>
<a href={FlowHelpers.pathFor( 'login' )}>Login</a>
</li>
</ul>
</div> );
}
}
);
Look at https://themeteorchef.com/snippets/authentication-with-react-and-flow-router/ for more details.

Geddy - create new item

I am an absolute beginner in node.js and geddy. I've followed a few tutorials and now I try to write something similar for my purposes.
When I try to create a new item, though, I get the following message:
/arithmetic_problem_types/function%20(id)%20%7B%20%20%20%20%20%20options.id%20=%20id;%20%20%20%20%20%20return%20helpersBase.urlFor.action(options);%20%20%20%20%7D not found.
I have no idea where this could come from. I've looked through the code and found nothing.
Controller:
var ArithmeticProblemTypes = function () {
this.respondsWith =[ 'html', 'json', 'xml', 'js', 'txt'];
this.index = function (req, resp, params) {
var self = this;
geddy.model.ArithmeticProblemType.all(function (err, arithmetic_problem_types) {
self.respond({
params: params, arithmetic_problem_types: arithmetic_problem_types
});
});
};
this.add = function (req, resp, params) {
this.respond({
params: params
});
};
this.create = function (req, resp, params) {
var self = this, arithmetic_problem_type = geddy.model.ArithmeticProblemType.create({
name: '1', title: 'open', numberType: '1', numberRanges: '1', operators: '1', askedFor: '1', specialProblemCategory: '1', askedForNumDenomOrBoth: '1',
reducedFractions:'1', mixedFractions: '1'
});
arithmetic_problem_type.save(function (err, data) {
if (err) {
params.errors = err;
self.transfer('add');
} else {
self.redirect({
controller: self.name
});
}
});
};
....................................................................
};
exports.ArithmeticProblemTypes = ArithmeticProblemTypes;
add.html.ejs
<div class="hero-unit">
<%= partial('_form', {params: params}); %>
</div>
index.html.ejs
<div class="hero-unit">
<h2>Arithmetic Problem Types List</h2>
<%- linkTo('Create a new Aritmetic Problem Type', addArithmeticProblemTypePath, {class: 'btn pull-right'}) %>
</div>
<% if (arithmetic_problem_types && arithmetic_problem_types.length) { %>
<% for (var i in arithmetic_problem_types) { %>
<div class="row todo-item">
<div class="span8">
<h3><%- linkTo(arithmetic_problem_types[i].title, arithmeticProblemTypePath(arithmetic_problem_types[i].id)) %></h3>
</div>
<div class="span4"><h3><i class="icon-list-alt"></i><%= arithmetic_problem_types[i].status; %></h3></div>
</div>
<% } %>
<% } %>
How can I get rid of that message and make it work?
EDIT:
This is the beginning of the _form.html.ejs file:
<%
var isUpdate = params.action == 'edit'
, formTitle = isUpdate ? 'Update this Arithmetic Problem Type' : 'Create a new Arithmetic Problem Type'
, action = isUpdate ? arithmeticProblemTypePath(params.id) + '?_method=PUT' : arithmeticProblemTypePath
, deleteAction = isUpdate ? arithmeticProblemTypePath(params.id) + '?_method=DELETE' : ''
, btnText = isUpdate ? 'Update' : 'Add'
, nameValue = isUpdate ? arithmeticProblemTypePath.name : ''
, errors = params.errors;
%>
<form id="arithmetic-problem-type-form" class="form-horizontal" action="<%= action %>" method="POST">
....
</form>
EDIT2:
Inspecting the page where I should write the name of the item and click the add button, I've found this
<div class="hero-unit">
<form id="arithmetic-problem-type-form" class="form-horizontal" action="function (id) {
options.id = id;
return helpersBase.urlFor.action(options);
}" method="POST">
<fieldset>
<legend>Create a new Arithmetic Problem Type</legend>
<div class="control-group">
<label for="title" class="control-label">Title</label>
<div class="controls">
<input class="span6" name="name" placeholder="enter name" type="text">
</div>
</div>
<div class="form-actions">
<input class="btn btn-primary" type="submit" value="Add">
</div>
</fieldset>
</form>
</div>
Indeed the message comes from the action attribute of the form element, but how can I solve it?
The message is telling you that the requested URL could not be found. AKA 404
/arithmetic_problem_types/function%20(id)%20%7B%20%20%20%20%20%20options.id%20=%20id;%20%20%20%20%20%20return%20helpersBase.urlFor.action(options);%20%20%20%20%7D
is definitely not a nice looking url. So i'm assuming there's something wrong with your form's action attribute. If that's what happened when you validate the form.
If that's what happened when you click the link to "Create a new arithmetic problem type" then you should probably put parenthesis after addArithmeticProblemTypePath

Symfony2.1 FosUserBundle translation broken

I had a project with Symfony 2.0 and FOSUserBundle 1.2.0, and everything was working fine. When I upgraded to the latest Symfony 2.1 version and the latest FOSUserBundle from the master branch, after fixing lots of stuff, the labels are not being translated, i.e. "form.username".
I had the User Bundle overwritten by a custom bundle I made. I've overwritten the following stuff:
Controller
ChangePasswordController
GroupController
RegistrationController
UserController
Form
Type
ChangePasswordFormType
RegistrationFormType
Resources
config
routing.yml
views
ChangePassword
changePassword_content.html.twig
changePassword.html.twig
Form
form_group.html.twig
form_user.html.twig
Group
edit.html.twig
list.html.twig
new.html.twig
show.html.twig
Registration
checkEmail.html.twig
email.txt.twig
register_content.html.twig
register.html.twig
User
edit.html.twig
index.html.twig
show.html.twig
I also have a custom user and group entity, and my custom UserType and GroupType which I omitted in the previous tree.
The translation files where at app/Resources/translations/FOSUserBundle.en.yml
I also tryed copying them to my bundle, src/Acme/UserBundle/Resources/translations/FOSUserBundle.en.yml
None of them is working with symfony 2.1.
Of course I cleaned the cache, the production cache, and regenerated assets just in case and refreshed the browser... Everything several times and nothing.
I searched here and on Google and I can't find any clues, I tried some things but without success.
I will copy the contents of some of the files below.
Acme/UserBundle/Controller/RegistrationController.php
<?php
namespace Acme\UserBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
class RegistrationController extends BaseController
{
public function registerAction()
{
$form = $this->container->get('fos_user.registration.form');
$formHandler = $this->container->get('fos_user.registration.form.handler');
$confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$user = $form->getData();
$authUser = false;
if ($confirmationEnabled) {
$this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$route = 'fos_user_registration_check_email';
} else {
$authUser = true;
$route = 'AcmeUserBundle_admin_user_index';
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$url = $this->container->get('router')->generate($route);
$response = new RedirectResponse($url);
if ($authUser) {
$this->authenticateUser($user, $response);
}
return $response;
}
return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
'form' => $form->createView(),
));
}
}
Acme/UserBundle/Form/Type/RegistrationFormType.php
<?php
namespace Acme\UserBundle\Form\Type;
use Doctrine\ORM\EntityManager;
class RegistrationFormType extends BaseType
{
private $entityManager;
public function __construct($class, EntityManager $entityManager)
{
parent::__construct($class);
$this->entityManager = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle', 'error_bubbling' => true))
->add('nombre', 'text', array('error_bubbling' => true))
->add('apellido', 'text', array('error_bubbling' => true))
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle', 'error_bubbling' => true))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
'error_bubbling' => true,
))
->add('groups', 'entity', array(
'class' => 'Acme\\UserBundle\\Entity\\Group',
'property' => 'name',
'label' => 'Grupos',
'empty_value' => 'Seleccione Grupos',
'multiple' => true,
'expanded' => true,
'required' => false,
));
}
public function getName()
{
return 'acme_user_registration';
}
}
Acme/Resources/views/Registration/register_content.html.twig
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="fos_user_registration_register">
<div class="content no-padding" {{ block('container_attributes') }}>
{{ form_widget(form) }}
</div>
<div class="actions">
<div class="actions-left" style="margin-top: 8px;"></div>
<div class="actions-right">
<input type="submit" value="{{ 'registration.submit'|trans({}, 'FOSUserBundle') }}" />
</div>
</div>
Acme/Resources/views/Registration/register.html.twig
{% extends "AcmeAdminBundle:Base:base_auth.html.twig" %}
{% form_theme form 'AcmeUserBundle:Form:form_user.html.twig' %}
*[...] Here are stylesheets and JS[...]*
{% block main_content %}
<!-- Start of the main content -->
<div id="main_content">
<h2 class="grid_12">{% block title "Crear Usuario" %}</h2>
<div class="clean"></div>
<div class="grid_6">
<div class="box">
<div class="header">
<img src="{{ asset('bundles/acmeadmin/img/icons/packs/fugue/16x16/ui-text-field-format.png') }}" alt="" width="16"
height="16">
<h3>Información Básica</h3>
<span></span>
</div>
{% block fos_user_content %}
{% include "AcmeUserBundle:Registration:register_content.html.twig" %}
{% endblock fos_user_content %}
</div> <!-- End of .box -->
</div> <!-- End of .grid_6 -->
</div> <!-- End of #main_content -->
<div class="push clear"></div>
{% endblock main_content %}
If I disable my bundle, removing
public function getParent()
{
return 'FOSUserBundle';
}
the labels appear translated as expected. I don't know what else to do. Any Suggestions?

Resources