How to generate a form by Blade template engine without generating action attribute?
I would like to generate a form just for ajax request.
1) If you dont want the form to submit
{{ Form::open(['onsubmit' => 'return false']) }}
2) If you have a ajax function, you can call it like so
{{ Form::open(['onsubmit' => 'yourAjaxFunction(); return false']) }}
3) If you want to include Angular JS directive to the form
{{ Form::open(['ng-submit' => 'submit()', 'onsubmit' => 'return false']) }}
No, it's actually not possible to tell the Form builder to omit the action attribute. Some attributes will be set in any case, and the action-attribute is one of them. Here's the relevant part from the function:
public function open(array $options = array())
{
//....
$attributes['method'] = $this->getMethod($method);
$attributes['action'] = $this->getAction($options);
$attributes['accept-charset'] = 'UTF-8';
//....
return '<form'.$attributes.'>'.$append;
}
Source: https://github.com/illuminate/html/blob/master/FormBuilder.php#L104
But you can easily overwrite it by just passing in a 'url':
Form::open(['url' => '#'])
Note: Overwriting the action like Form::open(['action' => '#']) would throw an error because this specifies the name of a route. url specifies the raw url.
Related
I am using Mail::send function to send emails to my end users with dynamically generated links in them Below is my sample code for the function -
$myemail = "some email adderess";
$myurl = "some url that will be emailed";
Mail::send('emails.mybladetemplate', ['myemail' => $myemail] , function ($message) use ($myemail){
$message->subject('Your favorite links');
$message->from('someone#company.com', 'Company');
$message->to($myemail);
});
I am having trouble passing $myurl to the blade template and publishing it. I even used HTML{{ }} in my blade template but no success. I have tested Mail::send with other templates and it works fine. Just not when I pass the variables.
Added ['myemail' => $myemail, 'myurl' => $myurl] and use ($myemail, $myurl) to solve for it.
<form method="post" action="{{action('PLAYERController#update', $ply->reg_no)}}">
{{csrf_field()}}
Getting method not allowed exception on custom validation with false return. Tried mentioning PUT, PATCH and DELETE inside csrf field. Still, does not work.
UPDATE
using post for form method. Using method_field('POST'). not defining get method for the update function. If I go back from the error page back to the form page and press refresh, then the validation message is displayed as it should.
UPDATE 2
Validator::extend('check_sold_amount', function($attribute, $value, $parameters, $validator) {
if(($value%5000)==0)
{
return true;
}
return false;
});
}
UPDATE 3
Controller code
public function update(Request $request, $reg_no)
{
//
$this->validate($request, [
'sold_amount' => 'required|check_sold_amount',
'sold_to_team'=>'required'
]);
$ply = Player::find($reg_no);
$ply->sold_amount = $request->get('sold_amount');
$ply->sold_to_team = $request->get('sold_to_team');
$team_name=$ply->sold_to_team;
$team=Team::find($team_name);
if($ply->category=='indian')
{
$team->indian_players=$team->indian_players+1;
}
else {
$team->foreign_players=$team->foreign_players+1;
}
$team->balance=$team->balance-$ply->sold_amount;
$ply->save();
$team->save();
//return view('player.index');
}
Method not allowed means you do not have a route set up for the request that happened. There are 2 possibilities:
The route for the form submission is not set up
The code you have shown us does not include any method_field(...), so it looks like you are doing a normal POST. So you need a corresponding POST route like:
Route::post('/some/path', 'PLAYERController#update');
The route for the failed validation response is not set up
I'm guessing this is the problem. Say you are on pageX, and you landed here via a POST. You have a post route set up, so that you can land on this page OK. Now from this page, you submit the form you have shown us, but validation fails. When that happens, Laravel does a GET redirect back to pageX. But you have no GET route set up for pageX, so you'll get a Method not allowed.
Along with your POST route for the current page, you need a GET route to handle failed validations.
Also, you say Tried mentioning PUT, PATCH and DELETE inside csrf field - as others pointed out, you should use method_field() to spoof form methods, eg:
<form ...>
{{ csrf_field() }}
{{ method_field('PATCH') }}
Laravel form method spoofing docs
UPDATE
Based on your comments, I think it is actually your initial POST that is failing. Checking your code again, I think your action() syntax is incorrect.
According to the docs, if the method specified in the action() helper takes parameters, they must be specified as an array:
action="{{ action('PLAYERController#update', ['reg_no' => $ply->reg_no]) }}"
If your update route using patch method (example Route::patch('.....');) then add this {{ method_field('PATCH') }} below {{csrf_field()}} in your update form
UPDATE
If you are not using PATCH method for the update route, try this :
Route::patch('player/update/{reg_no}', 'PLAYERController#update')->name('plyupdate');
and then in the form you can do like below :
<form method="POST" action="{{route('plyupdate', $ply->reg_no)}}">
{{csrf_field()}}
{{ method_field('PATCH') }}
//Necessary input fields and the submit button here
</form>
This way always works fine for me. If it still didn't work, maybe there's something wrong in your update method in the controller
UPDATE
Untested, in your update method try this :
public function update(Request $request, $reg_no) {
$input = $request->all();
$ply = Player::find($reg_no);
$validate = Validator::make($input, [
'sold_amount' => 'required|check_sold_amount',
'sold_to_team'=>'required'
]);
if ($validate->fails()) {
return back()->withErrors($validate)->withInput();
}
$ply->sold_amount = $request->get('sold_amount');
$ply->sold_to_team = $request->get('sold_to_team');
$team_name=$ply->sold_to_team;
$team=Team::find($team_name);
if($ply->category=='indian') {
$team->indian_players=$team->indian_players+1;
}
else {
$team->foreign_players=$team->foreign_players+1;
}
$team->balance=$team->balance-$ply->sold_amount;
$ply->save();
$team->save();
return view('player.index');
}
Don't to forget to add use Validator; namespace
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show the profile for the given user.
........................
Did you reference a validation request controller?
Hope this helps :)
I'm creating search form in laravel.
After form submit I want to get /search/{search_phrase} URL, i.e /search/cats
How do I create such URL in controler or by submitting form ?
I've tried for now (in controller) return view('search.index', ['search' => $search]); but this didn't worked.
I know I can pass variable this way: {{ Form::open(['action' => 'VentureController#searchByField', $search]) }} but this would be predefined variable and it is not working in this situation.
Form actions always confused me as it seemed very simple just to specify the controller however, every time I use it I always get Route [Controller#method] not defined. So I always go and manually make the route then use a url for my forms.
I currently have a route set up as Route::controller('handle/events', 'EventsController') and I'm trying to call the method postAdd from a form like:
{{ Form::open(['action' => 'EventsController#postAdd']) }}
instead of using
['url' => 'handle/events/add'] which is perfectly acceptable given that this is a RESTful route.
When I use the action, Laravel throws Route [EventsController#postAdd] not defined.. The method postAdd in the EventsController also accepts a parameter which I would like to pass in the form.
In the controller, the method is
public function postAdd($staff = false) {
var_dump($staff); // Always false
}
and once again I thought it would be as simple as:
{{ Form::open(['url' => 'handle/events/add'], true) }} however it did not change the value of $staff.
Recap
I would like to change my forms to point to controller methods rather than urls.
I would like to pass a parameter with my forms.
First Problem can be solved by naming your routes.
For example: Route::post('handle/events/add',['as' => 'handle.event.add', 'uses' => 'EventsController#addMethod']);
Then in your form you can do something like this
{{ Form::open(array('route' => 'handle.event.add', 'method' =>'POST'))}}
Now your form will use EventsController#addMethod
Docs named routes
If you want to pass a parameter to the controller method you can define it in your route
Route::get('handle/{event}',['as' => 'handle.event.add', 'uses' => 'EventsController#addMethod'])
Now your addMethod expects a paramter.
I'm having trouble posting forms using Laravel 4.1 with the blade template engine. The problem seems to be that the full URL including http:// is being included in the form action attribute. If I hard code the form open html manually and use a relative url, it works OK, however, when it has the full url, I am getting an exception.
routes.php
Route::any("/", 'HomeController#showWelcome');
HomeController.php
public function showWelcome()
{
echo($_SERVER['REQUEST_METHOD']);
return View::make('form');
}
Form opening tag in form.blade.php
{{ Form::open(["url" => "/","method" => "post","autocomplete" => "off"]) }}
{{ Form::label("username", "Username") }}
{{ Form::text("username", Input::old("username"), ["placeholder" => "john.smith"]) }}
{{ Form::label("password", "Password") }}
{{ Form::password("password", ["placeholder" => ""]) }}
{{ Form::submit("login") }}
{{ Form::close() }}
So if I go to my home dir / in the browser, I see the form that I have created. If I fill in the form details and click submit, I am simply taken to the same page - the request method is still GET as shown by echo($_SERVER['REQUEST_METHOD']);
I notice that the full
http://localhost/subdir/public/
url is used in the form markup. If I hardcode a form open tag in such as
<form action="/subdir/public/" method="post">
it works fine and $_SERVER['REQUEST_METHOD'] shows as post.
What am I doing wrong here?
You have created the route for the post?
example:
{{Form::open(["url"=>"/", "autocomplete"=>"off"])}} //No need to later add POST method
in Route.php
Route::post('/', 'YouController#postLogin');
you have not set up a route to handle the POST. You can do that in a couple of ways.
As pointed out above:
Route::post('/', 'HomeController#processLogin');
note that if you stick with your existing Route::any that the `Route::post needs to be before it as Laravel processes them in order (I believe).
You could also handle it in the Controller method showWelcome using:
if (Input::server("REQUEST_METHOD") == "POST") {
... stuff
}
I prefer the seperate routes method. I tend to avoid Route::any and in my login pages use a Route::get and a Route::post to handle the showing and processing of the form respectively.