Symfony2, Twig, Routes, Create valid url from twig with slug - forms

question is how to create such route as hpp://localhost/search/{searchString}
I played around but...
Simple form is (twig)
<form class="form-search" action="{{ path ('site_search') }}" method="get">
<input type="text" name="string" value="{% trans %}Search{% endtrans %}..."/>
</form>
Route is
site_search:
pattern: /search/{string}
defaults: { _controller: MainSiteBundle:Search:default, string: null }
methods: [GET]
Now i get such url http://local.site/search?string=some but i want get http://local.site/search/some
Or what is the best solution for _GET form url ?

That's the way html works .. form method get will append ?inputname=inputvalue and post will send a post request to the given action url. ( but not append something to the action like /inputvalue )
you could change the form action dynamically with javascript or use a RewriteRule in your webserver configuration in order to achieve what you're looking for.
A url rewrite might be the better option in my oppinion. Users directly accessing /search/term will not be redirected, users submitting the form will and therefore see the correct url in their browsers.
Why not just use method="post" and inside your action redirect the user to /search/term.
public function searchAction($string = null, Request $request)
{
if ( !($request->get('string') && !($string) ) {
// ... render your form here
// return form
}
// ... perform search here
// return search results
}
That's how search is usually implemented with a form. Post the search-term get redirected to the results.

Related

Method override for expressJS not working for PUT hidden method HTML FORM

Using express and mongoose/mongo to create a todo app. Domain model: Authors have reminders.
In my app.js:
var bodyParser = require('body-parser')
var methodOverride = require('method-override')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))
app.use(methodOverride('_method'))
my form using handlebars in views/authors/edit.hbs:
<h2>Edit {{name}}</h2>
<form action="/authors/{{_id}}" method="post">
<input type="hidden" name="_method" value="put">
<label>Name:</label>
<input type="text" name="name">
<input type="submit">
</form>
My routing for the edit view and put request to update author:
app.get("/authors/:id/edit", function(req, res){
AuthorModel.findById(req.params.id, function(err, docs){
res.render("authors/edit", docs)
})
})
app.put("/authors/:id", function(req, res){
console.log("updating")
AuthorModel.findById(req.params.id, function(err, docs){
docs.name = req.body.name
docs.save(function(err){
if(!err){
res.redirect("authors/" + req.params.id)
}
})
})
})
When I inspect the elements in the dev tools I see everything I need to see, but when I go to submit, gives me error CANNOT POST. Create functionality works fine, so my first thought is the method override isn't working. If I change put to POST, everything works great.
If it helps, link to the repo that contains this app
Judging by the documentation, there are two common ways to override the method:
using a header;
using a query string parameter;
You're using the "old" method of specifying a form variable, which you can still use, but this requires custom logic on the server side.
It seems to me that the easiest way for you to fix this is to use the query string parameter:
<form action="/authors/{{_id}}?_method=put" method="post">

Submit a Form to Custom URL in Laravel 4

I have a simple form which allows the User to enter from_date and to_date.Lets say a user enters 2014-09-01 and 2014-09-10 respectively.
How can I get this form submit to a URL ../from_date/2014-09-01/to_date/2014-09-10
You cannot do that but if you need to do something like this, you need to submit to standard class Controller and then resubmit it using redirection:
public function resubmit() {
Redirect::to('/from_date/'.Input::get('from_date').'/to_date/'.Input::get('to_date'))->withInput();
}
But to be honest I don't know why you try to do that. Usually you post data to static url and display content using dynamic urls with pretty urls.
To change the URL once the page has already loaded, you will need to use javascript, as you won't be able to do this using Laravel/PHP because you need access to the dates, which are only selected after the page has loaded.
If your form is similar to:
<form id="dateForm" onsubmit="return submitDateForm()">
<input type="text" id="from_date" name="from_date">
<input type="text" id="to_date" name="to_date">
</form>
Assuming you are using POST for the form submission, and have already imported jQuery, then insert into your view (or a separate .js file which you import) the following jQuery:
function submitDateForm() {
var from_date = $( '#from_date' ).val();
var to_date = $( '#to_date' ).val();
//Send the request
var request = $.post("../from_date/" + from_date + "/to_date/" + to_date);
//prevent the form from submitting itself normally
return false;
}

Play framework. How to check if user is authenticated or not?

I'm new to playframework and I'm using version 2.2.2.
I'm checking the zentask sample but could somebody tell me how to check in view if user is logged in or not?
In main.scala.html I've list of links.
<ul>
<li>New blogpost</li>
<li>Login</li>
<li>Logout</li>
</ul>
What I would like to have is that when user is logged in the logout link is shown.
My application.scala looks like this:
def index = Action {
Ok(views.html.index(BlogPost.all(), blogpostForm))
}
I can check that if user is allowed to access to create new blogpost:
def newBlogpost = IsAuthenticated { username => _ =>
User.findByUsername(username).map { user =>
Ok(views.html.blogpost.item(blogpostForm))
}.getOrElse(Forbidden)
}
So what would be the easiest way in main.scala.html to check if user is logged in or not and show correct link based on that?
You can pass session to you html template and check is defined user there or not:
#()(implicit session: Session)
<ul>
#session.get("user").map { user =>
<li>New blogpost</li>
<li>Logout</li>
}.getOrElse{
<li>Login</li>
}
</ul>
Note: you have to mark request in your action as implicit.

Why do i not get through to my Meteor.method on the server?

I'm trying to add a url to the logged in users collection. My final goal at least is to be able to add a field e.g {profilePicture: 'http://randompic.com/123.png'}
What i've tried so far is:
<template name="profile">
<h1>My Profile</h1>
<form class="form-inline"action="">
<label for="url"></label>
<input class="input input-large" type="url" name="url" placeholder="URL for you image..." id="url">
<button class="btn btn-success submit">Update profile picture</button>
</form>
</template>
When the user will press the Update profile picture -button i send it to this helper function:
Template.profile.events({
'click .submit': function (evt, tmpl) {
var userid = Meteor.userId();
var url = tmpl.find('#url').value;
var options = {_id: userid, profilePicture: url};
Meteor.call('addToProfile', options);
}
});
I have tried to alert out option._id and options.profilePicture and i have that data availble.
Now when i pass it along to my server.js file i get no output of my alert:
Meteor.methods({
'addToProfile': function(options) {
//Not even this alert will show..
alert(options._id); Edit: console.log() works on the server thought.
}
})
So that is my first issue.
The second problem (to come) is that i don't know how to update/add to the users collection with this profilePicture data. Would really appreciate if someone could contribute with a small example of that part.
Based on the comments everything seems to be functioning as expected. It appears that you are just trying to update some user data on the client. Since you have the insecure package removed you need to validate the updates on the server (that the client requests), this is how you would do that:
// only applies to client requests
Meteor.users.allow({
// validation for user inserts
insert: function ( userId, doc ) {
// perform any checks on data that you want to perform, like checking to see if the current user is an admin.
// this check just requests that a user be logged in
return userId;
}
,
// is your validation for user updates
update: function ( userId, doc, fields, modifier ) {
// again, perform any validation you want. A typical check is to make sure they didn't add any extra fields.
// this makes sure a user is logged in and that they are only attempting to update themself
return userId === doc._id;
}
});
There are some more thorough examples in the docs. Now you can just call update like you normally would and rely on the server to perform any validation!

Error with jQuery $.get

i can navigate to
https://www.facebook.com/plugins/likebox.php?id=20531316728 via my browser
but cant use jQ $.get , (not working with the specific url)
url='https://www.facebook.com/plugins/likebox.php?id=20531316728&width=292&height=258&colorscheme=dark&show_faces=true&border_color&stream=false&header=false';
$.get(url, function(data){alert(data);} );
can i use any method to fetch the url (js is preferred ) ? any idea?
Simple, You cannot make cross domain ajax calls.
There are 2 options:
1) Try with JSONP Read - http://api.jquery.com/jQuery.getJSON/
2) Make an ajax call to your site URL where you can use CURL to facebook URL to get the data.
we could not access the cross domain data with ajax request
$.get("your_cross_domain_url",function(response)
{
});
So, you have to use a local file to accessing the cross domain data.
var content="your_url";
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
// Filtering URL from the content using regular expressions
var url= content.match(urlRegex);
if(url.length>0)
{
// Getting cross domain data
$.get("urlget.php?url="+url,function(response)
{
// do your stuff
});
and the urlget.php file should be like this
<?php
if($_GET['url'])
{
$url=$_GET['url'];
echo file_get_contents($url);//loading the URL data.
}
?>