I have a edit form with some checkboxes that I am trying to make checked when the associated many to many relationship is established.
Distributors belong to many beers
Beers belong to many distributors
in my controller I have:
$breweries = Brewery::lists('name', 'id');
$all_dist = Distributor::all();
$beer = Beer::find($id);
$distributions = [];
foreach ($beer->distributors as $distributor)
{
$distributions[$distributor->id] = BeerDistribution::where('beer_id', '=', $beer->id)
->where('distributor_id', '=', $distributor->id)->first()->price;
}
return View::make('beers.edit', ['beer' => $beer, 'distributors' => $all_dist, 'distributions' => $distributions, 'breweries' => $breweries, 'styles' => $styles]);
and I in my edit form I have:
{{ Form::model($beer, ['route' => ['beers.update', $beer->id], 'method' => 'PATCH']) }}
#foreach ($distributors as $distributor)
<?php $carried = in_array($distributor->id, array_keys($distributions)) ? true : false ?>
{{ Form::checkbox('distributors[]', $distributor->id, $carried); }}
{{ Form::label($distributor->name) }}
{{ Form::label('price' . $distributor->id, 'Retail:') }}
<?php $price = $carried ? $distributions[$distributor->id] : null ?>
{{ Form::text('price' . $distributor->id, $price ) }}
#endforeach
{{ Form::submit('Save') }}
{{ Form::close() }}
Basically I am passing an associated array of each distributor_id => price. This array also tells me which distributors the beer already belongs to so that I can mark those checked off in my edit form.
Here's where things get wonky. When I load this form, all the checkboxes will be checked no matter what. If I change my controller loop to this:
foreach ($beer->distributors()->lists('distributor_id') as $distributor_id)
Then I can do create my array.
Why does calling $beer->distributors in the controller would result in all the checkboxes being checked?
The problem is with the last argument : $carried
{{ Form::checkbox('distributors[]', $distributor->id, [ "checked" => $carried ]); }}
Pass the last parameter as array, and tell it exactly which attribute to modify and the attribute value.
Related
I have json column where i save my orders data in it, code below is sample of that data:
[{"id":27,"name":"new product","price":7246,"quantity":"1","attributes":[],"conditions":[]}]
with code above if i have such loop in my edit page i'm able to get orders info:
#foreach($order->product_data as $data)
{{ $data['quantity'] }}
#endforeach
until here everything is good, but the problem when comes that my order has attributes "attributes":[], then i get this error:
Invalid argument supplied for foreach()
and my data in json column is like:
"[{\"id\":29,\"name\":\"effewf\",\"price\":24524,\"quantity\":\"1\",\"attributes\":[{\"attr\":{\"label\":\"Red\",\"price\":\"5000.00\"}},{\"attr\":{\"label\":\"22\\\"\",\"price\":\"900000.00\"}}],\"conditions\":[]}]"
as you see this order has 2 attributes. (can be more or less).
additional
this is how i get those data in order model:
protected $casts = [
'product_data' => 'array',
];
any idea why i get that error and how i can get my attributes data no matter if my order has attribute or not?
UPDATE
if i open edit page of order without attribute and dd the result will be like:
array:6 [▼
"id" => 27
"name" => "new product"
"price" => 7246
"quantity" => "1"
"attributes" => []
"conditions" => []
]
if load the same on order with attributes get the error above.
You should only allow to print data if exists and having the format we are expecting ,please add necessary conditions to your code like below which may prevent from getting the errors
Assuming the array you have in post is data you need to print.
#if($order->product_data) // check product_data value or not , also add key exists if needed
#if(is_array($order->product_data)) // check for product_data is array or not
#foreach($order->product_data as $data)
{{ $data['quantity'] // if array }}
{{ $data->quantity // if object }}
#if($data->attributes)
#foreach($data->attributes as $attribute) // loop through attributes
{{ $attribute->nameOfTheProperty // if object }}
#endforeach
#endif
#endforeach
#endif
#endif
But better to handle the data in controller if possible
update:
you need to convert your data into array, as your attribute property will be blank array if not having value otherwise it will be stdObject.
so your code should be : ($order->product_data should be an array if not then convert it to an array)
#if($order->product_data)
#if(is_array($order->product_data)) // assuming array
#foreach($order->product_data as $data)
{{ $data['quantity'] // if array }}
#if(count($data['attributes']) > 0) // **checked for blank array**
#foreach($data->attributes as $attribute) // loop through attributes
{{ $attribute['attr']['label'] }}
{{ $attribute['attr']['price'] }}
#endforeach
#endif
#endforeach
#endif
#endif
Tried with your sample data, and that executed without any error.
$json = "[{\"id\":29,\"name\":\"effewf\",\"price\":24524,\"quantity\":\"1\",\"attributes\":[{\"attr\":{\"label\":\"Red\",\"price\":\"5000.00\"}},{\"attr\":{\"label\":\"22\\\"\",\"price\":\"900000.00\"}}],\"conditions\":[]}]";
$jsonAsArray = json_decode($json, true);
foreach ($jsonAsArray as $data) {
echo $data['quantity'] . "\n";
if (! empty($data['attributes']) ) {
if (is_array($data['attributes'])) {
foreach ($data['attributes'] as $attribute) {
echo $attribute['attr']['label'] . ' ' . $attribute['attr']['price'] . "\n";
}
}
}
}
Outputs:
1
Red 5000.00
22" 900000.00
In your case, the product_data is not cast as an array.
You could try Defining An Accessor in your Order model, and remove the cast property of product_data
public function getProductDataAttribute($value)
{
return json_decode($value, TRUE);
}
Or Manually decode the json in your loop
#foreach (json_decode($order->product_data, TRUE) as $data)
{{ $data['quantity'] }}
#if (! empty($data['attributes']))
#foreach ($data['attributes'] as $attribute)
{{ $attribute['attr']['label'] }} {{ $attribute['attr']['price'] }}
#endforeach
#endif
#endforeach
This is how I did mine (category is a json column in the DB):
<div class="category">
<ul class="list-group">
#foreach ( json_decode( $code->category ) as $category)
<li class="list-group-item d-flex justify-content-between align-items-center">
<span class="badge badge-secondary badge-pill">{{$category}}</span>
</li>
#endforeach
</ul>
</div>
You just have to json_decode your json column to get an array and iterate over it. that's it, cheers.
How do I display a list of books in laravel form builder selection?
BookController.php
$book_names = Book::all();
return View::make('books')->with('book_names', $book_names);
At the moment I only know how do manually input data:
{{ Form::select('book_name', array(
'book1' => 'book1',
'book2' => 'book2',
'book3' => 'book3')
}}
I want to do something like this:
{{ Form::select('book_name', array(
#foreach($book_names as $book_name)
$book_name->name => $book_name->name,
#endforeach
}}
But obviously It won't work..
Meet the lists() method. It allows you to create an array from one or two (key and value) properties of a collection:
$book_names = Book::lists('name');
return View::make('books')->with('book_names', $book_names);
And then simply pass that array:
{{ Form::select('book_name', $book_names) }}
I have a problem and I can't resolve it, please help me. So I have my form :
{{ Form::open(array('url'=>'/administration/student/addMarks','method' => 'post')) }}
#foreach($aObjectsInGroupe as $object)
{{ Form::hidden('id_object[]',$object->id) }}
{{ Form::label($object->name) }}
{{ Form::select('note[]', $aMarks, null, array('class'=>'form-control')) }}
<br />
#endforeach
{{ Form::hidden('id',$aOneStudent['id']) }}
{{ Form::submit('Add mark',array('class'=>'btn btn-primary')) }}
{{ Form::close() }}
In my StudentController I have a method for get the mark from student_id and object_id:
public function getMarkByStudentAndObject($nIdStudent, $nIdObject){
$aMark = \Mark::where('student_id', '=', $nIdStudent)
->and('object_id', $nIdObject)
->get()
->toArray();
}
$aMarsks it's a table :
$aMarks = array(
'0'=>'0',
'1'=>'1',
'2'=>'2',
'3'=>'3',
'4'=>'4',
'5'=>'5',
'6'=>'6',
'7'=>'7',
'8'=>'8',
'9'=>'9',
'10'=>'10',
);
It's possible to call the method getMarkByStudentAndObject in :
{{ Form::select('note[]', $aMarks, null, array('class'=>'form-control')) }}
to get the selected value?
Help me please. Thx in advance.
maybe you need to do this:
<select name="note[]" class="form-control">
#foreach($aMarks as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
You should also check your Eloquent query, instead of ->and use another ->where
Try the lists() function of the Query Builder
\Mark::where('student_id', '=', $nIdStudent)
->and('object_id', $nIdObject)
->lists('column_1', 'column_2');
You then get the values of column_1 as the keys of the array and column_2 as the values.
http://laravel.com/docs/4.2/queries#selects
You should be able to directly call this from the Form::select. A call to
Mark::getMarkByStudentAndObject($aOneStudent['id'], $object->id)->note
would give you the Mark object and then you would need to get the note column which stores the value in the Mark object. Resulting in a call like this:
{{
Form::select(
'note[]',
$aMarks,
Mark::getMarkByStudentAndObject(
$aOneStudent['id'],
$object->id
)->note, array('class'=>'form-control')
)
}}
At the moment I can't verify if this is working because I have no possibility to test it but it should work as Blade is just a wrapper for PHP calls.
I want to set check-boxes state from database, so I write,
{{ Form::checkbox('asap', null, $offer->asap) }}
But if I want to set 'id' to the check-box like
{{ Form::checkbox('asap', null, $offer->ASAP, array('id'=>'asap')) }}
It always set my check-box state to true. (Before user select it)
So question how set 'id' in blade check-boxes when check-box state is set before user select it?
I know this question was answered before, in this one I am going to explain step by step how to implement checkboxes with Laravel/blade with different cases ...
So in order to load your checkboxes from the database or to test if a checkbox is checked :
First of all you need to understand how it works, as #itachi mentioned :
{{ Form::checkbox( 1st argument, 2nd argument, 3rd argument, 4th
argument ) }}
First argument : name
Second argument : value
Third argument : checked or not checked this takes: true or
false
Fourth argument : additional attributes (e.g., checkbox css classe)
Example :
{{ Form::checkbox('admin') }}
//will produces the following HTML
<input name="admin" type="checkbox" value="1">
{{ Form::checkbox('admin', 'yes', true) }}
//will produces the following HTML
<input checked="checked" name="admin" type="checkbox" value="yes">
How to get checkboxes values ? ( in your controller )
Methode 1 :
public function store(UserCreateRequest $request)
{
$my_checkbox_value = $request['admin'];
if($my_checkbox_value === 'yes')
//checked
else
//unchecked
...
}
Methode 2 :
if (Input::get('admin') === 'yes') {
// checked
} else {
// unchecked
}
Note : you need to assign a default value for unchecked box :
if(!$request->has('admin'))
{
$request->merge(['admin' => 0]);
}
this is nice right ? but how could we set checked boxes in our view ?
For good practice I suggest using Form::model when you create your
form this will automatic fill input values that have the same names as
the model (as well as using different blade Form:: inputs ..)
{!! Form::model( $user, ['route' => ['user.update', $user->id], 'method' => 'put' ]) !!}
{!! Form::checkbox('admin', 1, null) !!}
{!! Form::close() !!}
You can also get it like this :
{{ Form::checkbox('admin',null, $user->admin) }}
Okey now how to deal with :
multiples checkboxes
Add css classe
Add checkbox id
Add label
let's say we want to get working days from our database
$working_days = array( 0 => 'Mon', 1 => 'Tue', 2 => 'Wed',
3 => 'Thu', 4 => 'Fri', 5 => 'Sat', 6 => 'Sun' );
#foreach ( $working_days as $i => $working_day )
{!! Form::checkbox( 'working_days[]',
$working_day,
!in_array($working_days[$i],$saved_working_days),
['class' => 'md-check', 'id' => $working_day]
) !!}
{!! Form::label($working_day, $working_day) !!}
#endforeach
//$saved_working_days is an array of days (have 7 days, checked & unchecked)
I've spent sometime to figure out how to deal with multiple checkboxes I hope this can help someone :)
3rd argument decides whether checkbox is checked or not. So probably $offer->ASAP (or $offer->asap is true (or not false or not null). If you want to to make checkbox unchecked either set it to false, or don't use 3rd argument (set to to null or false):
{{ Form::checkbox('asap',null,null, array('id'=>'asap')) }}
EDIT
Another possibility is that you have on your page some custom JavaScript code that finds element by asap id and checks this checkbox. So when you don't set id, JavaScript cannot check it, but when you set this id, the checkbox will be checked by JavaScript.
in FormBuilder.php
public function checkbox($name, $value = 1, $checked = null, $options = array())
{
return $this->checkable('checkbox', $name, $value, $checked, $options);
}
1st param: name
2nd : value
3rd : checked or not (i.e. null, false or true)
4th : attributes.
{{ Form::checkbox('asap',null,$offer->ASAP, array('id'=>'asap')) }}
your order is wrong.
it should be,
{{ Form::checkbox('asap',$offer->ASAP, null, array('id'=>'asap')) }}
Good luck!
<div class="togglebutton">
<label>
#if ($programmer->play === 1)
<input type="checkbox" name="play" checked="">
#else
<input type="checkbox" name="play" {{ old('play') ? 'checked' : '' }} >
#endif
Play
</label>
</div>
I have a form:
{ Form::open(array('action' => 'RatesController#postUserRate', $client->id)) }}
{{ Form::text('rate', '', array('placeholder' => 'Enter new custom client rate...')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
How do I pass my $client->id value through the form to my controller method?
I currently have a controller method that looks like this:
public function postUserRate($id)
{
$currentUser = User::find(Sentry::getUser()->id);
$userRate = DB::table('users_rates')->where('user_id', $currentUser->id)->where('client_id', $id)->pluck('rate');
if(is_null($userRate))
{
...
}else{
....
}
}
And the error log says "Missing argument 1 for RatesController::postUserRate()"
Any ideas on how to pass this $client->id into my controller so I can use it as I want to above?
Add {{ Form::hidden('id', $client->id) }}to the form. Then, when it's posted, you can fetch its value per usual with Input::get('id').
Also, remove the postUserRate method's argument.
You simply use :
Form::open(array('action' => array('Controller#method', $user->id)))
the variable $user->id is passed as argument to the method method, also this last one should recieve an argument as well, like so : method($userId)
Source : Laravel documentation