Form Model Binding for checkboxes - php

I'm using Laravel 4.1 and in my app I need to show a form with pre filled checkboxes. But I try to do it with using Form Model Binding, it doesn't work.
{{ Form::model($user, array('route' => 'settings-notify')) }}
<div class="formRow form-horizontal_row">
{{ Form::checkbox('notify_visit', '1') }}
</div>
<div class="formRow form-horizontal_row">
{{ Form::checkbox('notify_rate', '1') }}
</div>
<div class="formSubmit">
{{ Form::submit('Save') }}
</div>
{{ Form::close() }}
Is there any way to make it working?

I ended up handling this in my controller because as #Ladislav Maxa says in their comment to #Antonio Carlos Ribeiro the database never updates. This is because empty checkboxes are not submitted with the form so no 'unchecked' value is available for updating the database.
The solution I used is to check for the existence of the field in the get object. If it's there the box was checked.
$notify_rate = Input::get('notify_rate') ? 1 : 0;
$data['notify_rate'] = $notify_rate;
Another way I have done this before was to create a text input with the same name and a value of 0 before the checkbox. If the checkbox is unticked the text input value is submitted, if the checkbox is ticked it's value is used.
<input name="notify_rate" type="text" value="0">
<input name="notify_rate" type="checkbox" value="1">
That's probably not valid HTML though and I prefer dealing with this server side.

Works fine for me, here's a test I just did here:
Route::get('test', function() {
$user = User::where('email','myemail#domain.com')->first();
Form::model($user);
$user->notify_rate = true;
echo e(Form::checkbox('notify_rate'));
$user->notify_rate = false;
echo e(Form::checkbox('notify_rate'));
});
This is what I got:
<input checked="checked" name="notify_rate" type="checkbox" value="1">
<input name="notify_rate" type="checkbox" value="1">

Related

Laravel - How to get the value of input in a view

I'm building a page with 2 forms like this:
index.blade.php:
<form action="/" method="post">
<input type="text" list="cats" name="catipt" id="catipt" />
<datalist id="cats">
#foreach($categories as $category)
<option>{{ $category->name }}</option>
#endforeach
</datalist>
<button type="submit">Add</button>
</form>
#include("catForms")
catForms.blade.php contains a form aside from the first one, with a send button to send the form input via email. The second form in which there are many div that each has input for the user to fill in. The first form allows user to add items to the dropdown list, so it's a post method. Based on the input in the first form, a corresponding div in second form will show, others will hide, using Jquery. Now, I want to send the data from the user via email, but how do I get the value of the input in the first form in the email view so that I can filter out the irrelevant div? Otherwise, I'll have to list out all div even they are empty.
The problem is that, there are two forms, so there are two Request $request, I can't get the input value from the first form in email view. I tried this in email view, but this doesn't work:
#php
use Symfony\Component\Console\Input\Input;
#endphp
Cat: {{ Input::get('catipt') }}
<form action="/" method="post">
<input type="text" list="cats" name="catipt" id="catipt" />
<datalist id="cats" name="cat-name">
#foreach($categories as $category)
<option value="{{ $category->name }}">{{ $category->name }}</option>
#endforeach
</datalist>
<button type="submit">Add</button>
</form>

Laravel, Pass input variables from page to other using session

Please note that I'm new in Laravel, so I need serious help and since 3 days looking for solution but no luck.
All I need just to view or display the value of the input text from the form booking-form to customer/dashboard page, please note that can't send the input data untill you login and this is working fine, but how to pass data and display in the next page?
Please answer with code please
Form:
<form id="booking-form">
<input class="indexinput" type="text" id="country" name="country"
placeholder="Country">
<input class="indexinput" type="text" id="state" name="state"
placeholder="State">
<input class="indexinput" type="text" id="city" name="city" placeholder="city">
</form>
<button class="button getbids" >GET BIDS</button>
<script type="text/javascript">
$(document).on('click', '.getbids', function() {
var loggedIn = {{ auth()->check() ? 'true' : 'false' }};
if (loggedIn)
window.location.replace('customer/dashboard');
if(!loggedIn)
$('#loginModal').modal('show');
});
</script>
Route
Route::group(['middleware'=>['rolecustomer']], function () {
Route::get('/customer/dashboard', 'HomeController#index')->name('customer.dashboard');
});
controller:
public function index()
{
return view('index.customer.customerdashboard');
}
To store the value in the session, pass the value of the input to laravel's session like this.
Session::set('input_field', 'field_value');
And to retrieve the session use the following piece of code.
Session::get('input_field');
More informations on laravel session here.
If you want to put something something permanently for entire session, you can use $session->put('key', 'value').
In your case,
public function bids(Request $request){
$request->session()->put('country', $request->country);
$request->session()->put('state', $request->state);
$request->session()->put('city', $request->city);
return redirect()->route('route_name');
}
Then in next page, just, use Session::get($key).
<div>
<p>Country : {{ Session::get('country') }}</p>
<p>State: {{ Session::get('state') }}</p>
<p>City: {{ Session::get('city') }}</p>
</div>
Or, a more convenient way to access a Session is first check if the value is in the Session or not by Session::has('key_name').
<div>
<p>Country : {{ (Session::has('country') ? Session::get('country') : '' ) }}</p>
.....
</div>

How to get value of data attribute from button to controller in laravel

How can we get the data attribute value from button to controller in laravel
My button
<input type="submit" value="Add click" name="submit" id="submit" data-name="{{$value->name}}" data-click="{{$value->click}}">
i want to get data-click and data-name pass it to controller
$click=data-click;
$name=data-name;
from button attribute after submit form to controller
But the result not get the data-name and data-click value. How can we try this??
If you want to post those two data through Normal Form Post.Then use hidden input fields:-
<input type="hidden" value="{{$value->name}}" name="data-name"/>
<input type="hidden" value="{{$value->click}}" name="data-click"/>
Or:-
{{ Form::hidden('data-name', $value->name) }}
{{ Form::hidden('data-click', $value->click) }}
Now on Controller side you will get it as :-
$request->input('data-name')
$request->input('data-click');
You can use hidden field for this or you have to use ajax.
#if ($value != '')
{{ Form::hidden('somevalue', $value->name) }}
{{ Form::hidden('somevalueclick', $value->click) }}
#endif

Laravel: Repeating Fields (and Field Groups): Form Model Binding

I am building a form in Laravel that deals with an array field in the form of repeatable entities (whether it be single inputs or field groups). I am running into an issue using Form Model Binding when there is either a validation error with a repeated field or a different input in the form.
Right now I'm generating new "instances" of each field by pulling in the view partial with AJAX
# Add Feature
$(document).on 'click', '.js-listing__add-feature', (e) ->
e.preventDefault()
$.ajax
url: dashboard.partials.feature
type: 'GET'
success: (data) ->
$data = $(data)
$('.js-listing__features').append $data
return
return
# Removing features
$(document).on 'click', '.js-listing__remove-feature', (e) ->
e.preventDefault()
$(this).parent('.js-listing__feature-wrapper').remove()
return
So, a user can create new feature inputs on the fly which ultimately combine into an array when saved. The issue becomes when there is a validation issue in the form and we are redirected back. I have not found a way to access the features array in the state it was in (dynamic or not) to spit out what they previously had. In writing this, I guess the issue also becomes clearing out that field if it was the input itself causing the validation issue.
I've searched around in the docs and the 'ole Google for inspiration on this topic, but haven't come across anything. Any nudges in the right direction would be extremely helpful. Thanks as always!
Example of form
#extends('dashboard.master')
#section('content')
<h1>Edit Listing</h1>
#include('dashboard.partials.errors')
{!! Form::model($listing, ['method' => 'PATCH', 'route' => ['dashboard.listings.update', $listing->id], 'class' => 'uk-form']) !!}
<div class="uk-form-row">
{!! Form::label('price', 'Price') !!}
{!! Form::text('price') !!}
</div>
<div class="uk-form-row js-listing__features">
{!! Form::label('features', 'Features') !!}
#if ($listing->features && count($listing->features))
#foreach($listing->features as $key => $feature)
<div class="js-listing__feature-wrapper">
<input type="text" name="features[]" value="{{$feature}}">
<a class="js-listing__add-feature" href="#">+</a>
#if ($key > 0)
<a class="js-listing__remove-feature" href="#">-</a>
#endif
</div>
#endforeach
#else
<div class="js-listing__feature-wrapper">
<input type="text" name="features[]">
<a class="js-listing__add-feature" href="#">+</a>
</div>
#endif
</div>
<div class="uk-form-row">
{!! Form::submit('Update Listing') !!}
</div>
{!! Form::close() !!}
#stop
You'll see my take on what I'd do for the #foreach when I have values to display them when editing the listing. The issue here is not reading the values back (I have set/get attributes working fine for those), but how Form Model Binding works with input arrays so I can still have those values available when they have been dynamically added to the form with AJAX.
I had a similar problem some times ago... My code is surely not very elegant, but it worked ; it may help you to build something...
My trick was to generate a different name for items, distinguish old and new items, count new items:
<input type="text" name="E1-features"> // existing feature #1
<input type="text" name="N1-features"> // new feature #1
<input type="text" name="N3-features"> // new feature #3 (assuming user deleted #2)
<input type="hidden" name="counter" value="3"> // 3 features were added
Server side, the controller distinguishes the existing inputs from the new ones. Here is the code for the new inputs:
Input::flash();
// Existing features
foreach($features as $key => $feature){
if (Input::get('E'.$key.'-features')){
$rules['E'.$key.'-features'] = 'required';
}
}
// New features
for ($i = 1; $i <= Input::get('counter'); $i++) {
if (Input::get('N'.$i.'-features')){
$rules['N'.$i.'-features'] = 'required';
}
}
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
return Redirect::to('page')->withErrors($validator)->withInput();
}else{
// data stuff
}

Laravel - Setting Checked Property of Checkbox From Returned Array Input

I'm having a problem where I'm trying to handle a
return Redirect::to('page')->withInput();
call while using an array of checkboxes. Basically, if my validator fails, I want to return back, display some errors and repopulate inputs with their value. Here are the inputs I'm having difficulty with.
<div class="row">
<div class="col-xs-12">
<label class="checkbox-inline">
<input type="checkbox" name="rms_cs[]" value="Marshall and Swift Property Valuation" {{ (Input::old("rms_cs[]") == "Marshall and Swift Property Valuation") ? "checked":"" }}> Marshall & Swift Property Valuation
</label>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<label class="checkbox-inline">
<input type="checkbox" name="rms_cs[]" value="Premises Liability Survey" {{ (Input::old("rms_cs[]") == "Premises Liability Survey") ? "checked":"" }}> Premises Liability Survey
</label>
</div>
</div>
So, basically, I have multiple checkboxes, each with name="rms_cs[]" and value="something". How would I go about setting the checked property to checked when Input is returned?
Note: I have lots of text boxes and radio buttons that work fine, so I know that the issue doesn't lie with anything besides Input::old("rms_cs[]"). I think the issue is that rms_cs[] is an indexed array; ie rms_cs[0] = "Something" and not rms_cs["Premises Liability Survey"] = "Something"
If anyone could shed some light on this/provide a better way to handle something like this, that would be great.
You may use Laravel Form&HTML builder to achieve what you want, plus doing some extra work in your controller.
In your controller, you manually construct a checkbox array as follows:
$boxes = array();
$checkboxInput = Input::get('box');
foreach ($checkboxInput as $box) {
$boxes[$box] = true;
}
and then return with $boxes:
return Redirect::back()->withInput()->with('boxes',$boxes);
Next in your blade file, you use the Form class to set default checked value to either true or false like this:
{{Form::checkbox('box[]', 'box1', isset($boxes['box1']) && $boxes['box1'])}}
{{Form::checkbox('box[]', 'box2', isset($boxes['box2']) && $boxes['box2'])}}
And now you should see some checkboxes have been checked.
So, I ended up figuring this out. I changed
name="rms_ssp[]"
on each checkbox to:
name="rms_ssp[epis]"
name="rms_ssp[mrp]"
etc, so the array was no longer indexed. Then, I made a variable out of the old input:
<?php $rms_ssp = Input::old('rms_ssp'); ?>
And added this check in each of the checkboxes:
{{ (isset($rms_ssp['epis'])) ? "checked":"" }}
{{ (isset($rms_ssp['mrp'])) ? "checked":"" }}
And that did the trick.

Categories