Keep modal open after validation redirect - php

i am currently working on a project where the login/register is handled through modal boxes (so i click the login button and a nice modal reveals with a form in).
Im using foundation 5's reveal modal to house my login form but when the form is submitted and theres a validation error the modal closes. The reason this is happening is because i am redirecting back to the route where the login form is and in that route a button needs to be clicked to fire the modal.
What i was wondering is, is there something i can set so that modal stays open if there is a validation error or exception (account not found etc.) So if there is a validation error the modal stays open.
looking for any type of solution. my code is shown below.
Login function
public function postLogin()
{
// Declare the rules for the form validation
$rules = array(
'email' => 'required|email',
'password' => 'required|between:3,32',
);
// Create a new validator instance from our validation rules
$validator = Validator::make(Input::all(), $rules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
try
{
// Try to log the user in
Sentry::authenticate(Input::only('email', 'password'), Input::get('remember-me', 0));
// Get the page we were before
$redirect = Session::get('loginRedirect', 'dashboard');
// Unset the page we were before from the session
Session::forget('loginRedirect');
// Redirect to the users page
return Redirect::to($redirect)->with('success', Lang::get('auth/message.signin.success'));
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_not_found'));
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_not_activated'));
}
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_suspended'));
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_banned'));
}
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($this->messageBag);
}
Login modal
<div id="myModalLogin" class="reveal-modal small" data-reveal>
<h2>Login</h2>
<form method="post" action="{{ route('login') }}">
{{-- CSRF Token --}}
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
{{-- Email --}}
<label for="email"> Email
<input type="text" name="email" id="email" value="{{ Input::old('email') }}" />
</label>
{{ $errors->first('email', '<label class="error">:message</label>') }}
{{-- Password --}}
<label for="password"> Email
<input type="password" name="password" id="password" value=""/>
</label>
{{ $errors->first('password', '<label class="error">:message</label>') }}
{{-- Remember me --}}
<input name="remember-me" value="1" id="remember-me" type="checkbox"><label for="remember-me">Remember me</label>
<hr>
{{-- Form Actions --}}
<button type="submit" class="button">Sign in</button>
I forgot my password
<a class="close-reveal-modal">×</a>
</div>

You need to create a flag variable that you will pass to your view and set it true if you want the modal to auto open and set it false if you don't want to open it:
The problem with this is that ->with() doesn't work with Redirect::back() so we need a workaround: lets pass our flag variable as an input. For this you have to get all the old input and add the new flag variable to them. Make sure that the key (your flag variable name) doesn't already exist. You can check this with a var_dump(Input::all()).
$input = Input::all();//Get all the old input.
$input['autoOpenModal'] = 'true';//Add the auto open indicator flag as an input.
return Redirect::back()
->withErrors($this->messageBag)
->withInput($input);//Passing the old input and the flag.
Now in your view you have to print this "old" input into your JavaScript condition. If it exists it will print its value: true, otherwise it will print the second argument: false.
<script>
$(document).ready(function () {
if ({{ Input::old('autoOpenModal', 'false') }}) {
//JavaScript code that open up your modal.
}
});
</script>

You can return false; when you return the validations results.

Related

how to redirect and show error validateion in laravel

good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$product=new productModel();
// start add
$product->name=$request->input('name');
$product->save();
$add=$product->id;
$poducten=new productEnModel();
$poducten->id_product=$add;
$poducten->name=$request->input('name');
$poducten->price=$request->input('price');
$poducten->save();
$dataview['message']='data addes';
}else{
$dataview['message']='name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist

Laravel: Show or hide content depending on a Session variable

I'm doing a view that has a password protection. Basically when you access that resource, you have a view that indicates that you need to put a password.
The correct behavior of this should be
You access the View
The user enters the password and sends the POST form
If the method redirects back with certain value, you must see the real content of the page.
So my blade code is the following:
#if ($passedPassword = Session::get('passedPassword'))
...here goes the real/true view content
#else
<section class="questionnaire-questions">
<div>
<form
action="{{ route('questionnaire.password', ['questionnaire' => $questionnaire->id]) }}"
method="POST">
{{ csrf_field() }}
<h3 class="text-center">#lang('questionnaire.password.advice')<h3>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="goal-input-group numeric">
<label>PASSWORD</label>
<input
style='visibility: visible;'
name="password"
type="password"
>
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="goal-btn goal-btn-lg goal-btn-artic-blue">#lang('questionnaire.password')</button>
</div>
</form>
</div>
</section>
#endif
That view is rendered with the following method:
public function show(Questionnaire $questionnaire) {
$data = [];
$data['questionnaire'] = $questionnaire;
\Session::flash('passedPassword', false);
return view('questionnaires.show', array('data' => $data));
}
In the previous method I'm passing the passedPassword, but I can't find a way to pass it as a flash variable. If there is a way to add data like
return back()->with(array(
'passedPassword' => false
));
But using the view method I'll really appreciate to know how.
Then, when the user clics the button I call the next function:
public function password(Request $request, Questionnaire $questionnaire) {
if (strcmp($questionnaire->password, $request->input('password')) == 0) {
return back()->with(array(
'passedPassword' => false
));
}
}
But even when the password is correct, I got the password view, the flash/session variable never arrived to the view.
Is there something I'm missing or doing wrong?
Thanks in advance.
As Dan told me in the comments, I was setting to false the value of the session variable.
So first I remove the \Session::flash('passedPassword', false); during the show method.
Then I modify my blade logic. In my case sometimes the password is needed and sometimes not.
#if (($passwordLength === 0) || ($passwordLength !== 0 && Session::has('passedPassword')))
With that, If the resource has no password we let the user pass. Or in the case it has a password and also we have the passedPassword variable, we also let the user see the content.

PHP - Laravel: Getting a 403 forbidden error when trying to save javascript code to mysql database

I know that this is generally frowned upon, but for my specific reasons which I'll state below, I need this functionality:
So what we're doing on this website is that we are allowing users to buy "stores" on which they can sell products, and now those users want to add stuff like "Facebook Pixel" to their stores to allow them to track different activities.
Here's my form responsible for the code
<form action="{{ url('vendor/store/settings/analytics/update') }}" method="POST" style="margin-top: 30px;">
{{ csrf_field() }}
<div class="analytics-form">
<div class="col-md-8 col-md-offset-2 analytics-box">
<div class="form-group">
<label for="">Please pick a type of analytics to install:</label>
<select name="analytic_type[]" id="" class="form-control">
#foreach($analytic_types as $type)
<option value="{{ $type }}">{{ ucwords(str_replace('_', ' ', $type)) }}</option>
#endforeach
</select>
<br>
</div>
<div class="form-group">
<label for="">Please type/paste the code for this analytic:</label>
<textarea class="form-control" cols="5" rows="5" name="analytic_code[]" required></textarea>
<br>
</div>
</div>
</div>
<button class="btn btn-primary btn-block" id="applyAnalytics" type="submit" {{ $store->vendor->hasAnalytics() ? '' : 'disabled'}}>Apply Changes</button>
</form>
And here's the controller method I want to "hit":
public function updateAnalytics(Request $request)
{
try {
$store = auth()->user()->store;
auth()->user()->analytics()->delete();
if($request->has('analytic_type')) {
foreach($request->analytic_type as $index => $value) {
Analytics::create([
'user_id' => auth()->user()->id,
'analyticable_id' => $store->id,
'analyticable_type' => get_class($store),
'method_type' => $request->analytic_type[$index],
'method_code' => $request->analytic_code[$index],
]);
}
}
flash(__("Common.Saved_Successfully"));
} catch (\Exception $e) {
session()->flash('title', __("Common.Error"));
session()->flash('message', __("Common.An_Error_Happened"));
session()->flash('message-class', "error");
}
return redirect()->back();
}
This method works fine locally if I enter either normal text or code into the textarea, but if I tried to enter & submit the below block of code everything blows up, this block of code is the one provided by Facebook Pixel to its users, which I want to save in my database:
<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '339673053324500');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=339673053324500&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->
If I put the above code into the text area and submit the data to the server, I get this error below:
Forbidden
You don't have permission to access /app/public/vendor/store/settings/analytics/update on this server.
Additionally, a 403 Forbidden error was encountered while trying to
use an ErrorDocument to handle the request.
The server isn't even allowing me to hit the route in question, or any other route from this form as long as I am submitting code.
Note:
This is probably not an actual permission issue but a security related thing, because I've tried changing permissions on the server for all of the involved files from 0644 to 0755 and nothing changed, of course I might have done something wrong along the way, all suggestions are welcome.

redirect with old user input

I am trying to do a check to see if the user has any recorded violations or not.
I have got the flash massage to appear when the user id is entered, but I am having troubles when pressing the button, the entered ID is disappearing, I am trying to reload the page with the previously entered values.
Here is my view:
<strong>Customer ID:</strong>
<input class="form-control" type="text" name="custidno" id='cust' autocomplete="off" onkeypress="myFunction()" placeholder="Customer ID" value="{{ old('custidno') }}">
<a class="btn btn-info" href="{{ url('violationcheck') }}">Show</a>
#if(Session::has('flash_message'))
<div class="alert alert-success"><em> {!! session('flash_message') !!}</em></div>
#endif
and here is my controller:
public function violationcheck(Request $request)
{
$checked = violation::find($request->custidno);
if (!empty($checked))
Session::flash('flash_message','No violations.'); //<--FLASH MESSAGE
else {
Session::flash('flash_message','Ops, Found some violations.'); //<--FLASH MESSAGE
}
return redirect()->route('assignees.create')->withInput();
}
how do I redirect with to previous page and keep user input?
Whilst editing the controller code that you submitted about I noticed some missing curly braces in your if statement - try this and let me know if it works:
public function violationcheck(Request $request)
{
$checked = violation::find($request->custidno);
if (!empty($checked)) {
Session::flash('flash_message','No violations.'); //<--FLASH MESSAGE
} else {
Session::flash('flash_message','Ops, Found some violations.'); //<--FLASH MESSAGE
}
return redirect()->route('assignees.create')->withInput();
}

Display different errors based on which submit button has been clicked in Laravel 5.1

I hope you're all doing well and having a good festive season. I wanted to post a question to find out how I can display the errors for a particular form in Laravel 5.1 based on what submit button has been clicked. Here is some code to give a better explanation of what I'm trying to do.
<form action="{{ url( '/auth/login' ) }}" id="login" method="post">
#if (count($errors) > 0)
<div class="show validation-summary">
... display error container only when the login submit button has been clicked
</div>
#endif
<input name="submit" type="submit" value="Login" />
</form>
<form action="{{ url( '/auth/register' ) }}" id="register" method="post">
#if (count($errors) > 0)
<div class="show validation-summary">
... display error container only when the register submit button has been clicked
</div>
#endif
<input name="submit" type="submit" value="Register" />
</form>
Currently both validation divs are displaying when clicking the Login or Register submit buttons, but I only want to display the validation div which relates to that form that was submitted.
You can use a named error bag.
For example, in your controller you can do:
$validator = Validator::make(Input::all(), [
'some_input' => 'required',
], [
'some_input.required' => 'The input is required.',
]);
// ...some other code may go here
if($validator->fails())
{
return redirect()
->back()
->withInput()
->withErrors($validator, 'named_error_bag');
}
To display the errors in your named error bag in the view you can do.
#if(!empty($errors->named_error_bag->first('error_name')))
{{ $errors->named_error_bag->first('error_name') }}
#endif

Categories