I have a list of ten simple check boxes that all look something like this:
{{ Form::label('waterBox', 'Water:') }}
{{ Form::checkbox('waterBox', 'yes'); }}
{{ Form::label('calBox', 'Calories (kcal):') }}
{{ Form::checkbox('calBox', 'yes'); }}
I don't want the user to be allowed to check more than 5 boxes before submitting the form. How can I make it so that after a sixth box is checked one of the others is unchecked?
Randomly unchecking other checkboxes is a little confusing to your users.
How about disabling the other checkboxes instead?
var $checkboxes = $('input[type=checkbox]');
$checkboxes.change(function () {
if (this.checked) {
if ($checkboxes.filter(':checked').length == 5) {
$checkboxes.not(':checked').prop('disabled', true);
}
} else {
$checkboxes.prop('disabled', false);
}
});
Here's the fiddle: http://jsfiddle.net/F57s9/1/
P.S. If you're not using jQuery, just let me know and I'll whip you up a native solution.
You could call a javascript function (I'm using jQuery in this example) that looks at all the waterBox checkboxes and limits it to 5, something like this:
function limitCheckboxes()
{
var checkedBoxCount = $('[name=waterBox]:checked').length;
$('[name=waterBox]:checked').each(function () {
if ((checkedBoxCount > 5) &&
(this.checked))
{
this.checked = false;
checkedBoxCount--;
}
});
}
Then be sure to name your checkboxes with brackets:
{{ Form::checkbox('waterBox', 'yes', false, ['onclick' => 'limitCheckboxes()']); }}
I haven't tested this, but the general principle should work.
Update: fixed missing ID attribute on checkbox.
Update 2: fixed jQuery selection of checkboxes and counts.
Update 3: fiddle around and got a working example going. The code above should now reflect that. :) Added fiddle code: http://jsfiddle.net/Miggl/XKB7b/
Related
I want to automatically select a checkbox when the field in the database is filled in.
I am trying to use #if statement in the Form generator but it is not checking the checkbox.
Here is the code I am using:
{!! Form::checkbox('offer_made', 'offer_made', #if(empty($phase_2->offer_made)) 1 #endif) !!}
Im sending this over to the view in my Controller:
public function show(Order $order)
{
$order = Order::where('id', $order->id)->first();
$current_phase = $order->current_phase;
if($current_phase == 1) {
$phase_2 = Order_Phase_2::where('order_id', $order->id)->first();
return view('orders.phase-2', compact('order', 'phase_2'));
}
}
When I echo $phase_2->offer_made in the view it shows 1 so the value is coming through but the if statement is not working inside the Form builder.
Anyone knows how to fix this?
Thanks already!
You might be checking for the value incorrectly:
#if(empty($phase_2->offer_made)) 1 #endif)
This outputs a 1 if the value is empty. You should be checking for !empty() if I understand the field correctly.
So you might have success with this:
#if(!empty($phase_2->offer_made)) 1 #else 0 #endif)
Is the value 1/0 itself? Use $phase_2->offer_made directly as the third parameter.
use ternary operator as you cannot use blade syntax in php code. Try something like this:
{!! Form::checkbox('offer_made', 'offer_made',(!empty($phase_2->offer_made)) ? 'checked' : '') !!}
Pic 1
Pic2
The situation looks like this.
When sorting, I choose options "Like" and click submit. Everything is sorted nicely, but after refreshing the page, the value in the field is "Lastest".
Is there any possibility that the value I chose would remain until the next select.
You can use a session to keep the last selected value as the default value.
Here you can learn about the sessions.
I fixed it.
I add this to select:
<option href="/?sortMypost=1" value="1" {{ $option == '1' ? "selected" : "" }} >Latest</option>
And this to controller:
$option = request()->input('sortMypost');
And this to the end of the controller:
return view('posts.mypost', compact('posts', 'option'));
I found how to accomplish this on another site and I got it working. My issue is though that I need to use it in my edit form (preferably in the same form as my create form, since my create and edit views use the same form). When I go to my edit page, the "Section" dropdown value is selected as it should be. But the "Subsection" is not, because ofcourse I did not click it. Probably it's a fix too easy for me to see, but I am not quite good with javascript. I basically need the second dropdown (the subsection one) to show the correct options based on which "section" (first dropdown) is selected, on my edit view.
Section Model:
public function subsections()
{
return $this->hasMany('App\Subsection');
}
Subsection Model:
public function section()
{
return $this->belongsTo('App\Section');
}
View:
{!! Form::select('section_id', [null=>'-- Select Section --'] + $sections, null, array('id' => 'section')) !!}
<select id="subsection" name="subsection_id" class="select">
<option>-- First Select Section --</option>
</select>
From my controller: $sections = Section::lists('section', 'id');
Script:
<script>
$(document).ready(function($){
$('#section').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
$('#subsection').empty();
$.each(data, function(key, element) {
$('#subsection').append("<option value='" + key +"'>" + element + "</option>");
});
});
});
});
</script>
Route:
Route::get('api/dropdown', function(){
$id = Input::get('option');
$subsections = Section::find($id)->subsections;
return $subsections->lists('subsection', 'id');
});
If you just want to select the first option in jquery , you can add :
$('#subsection option:eq(1)').prop('selected', true);
Or else if you want to select a particular value, you can do that by
$('#subsection option[value="value_to_be_selected"]').prop('selected', true);
Use this after you have appended all the values to the subsection
In my controller I added:
$subsections = Subsection::where('section_id', '=', $transaction->section_id)->orderBy('subsection', 'asc')->lists('subsection', 'id');
And in my view I did this:
#if(isset($transaction))
{!! Form::select('subsection_id', [null=>'-- Select Subsection --'] + $subsections, null, array('class' => 'select', 'id' => 'subsection')) !!}
#else
<select id="subsection" name="subsection_id" class="select">
<option>-- First Select Section --</option>
</select>
#endif
Problem solved :)
So, what we will do is initially we will send value to the dependent drop-down as "<option value="">Select Something</option>"
and when returning on error create complete drop-down with selected as below value and return, this will reduce lots of javascript calls.
Controller:
if($error){
//create get array of second drop-down, suppose $second_drop
// create complete second drop-down like
$selectbox="";
foreach($second_drop as $option){
$selectbox.="<option value='". $option->id."'";
if($request->option2==$ $option->id){
$selectbox.=" selected ";
}
$selectbox.=">".$option->value."</option>";
}
}
return view('routename', ['selectbox2' => $selectbox]);
View:
<select id="subsection" name="subsection_id" class="select">
{!! $selectbox !!}
</select>
I am beginner in Phalcon framework, I have to validate form elements in .volt page
I have one form class file where I write hidden filed for record edit purpose, I'm storing record's id in hidden filed when its in edit mode
if ($options["edit"] == 1) {
// $tax_categories_id = new Hidden("tax_categories_id");
$this->add(new Hidden('tax_categories_id'));
//$this->add($tax_categories_id);
}
The problem is when I rendering this hidden filed in add.volt
{{ form.render('tax_categories_id')}}
Its working fine in time of edit mode, but in new record time its give error
Phalcon\Forms\Exception: Element with ID=tax_categories_id is not a part of the form
I know the why error is coming but i am not able to validate this field in .volt file
In the controller can you set your $options variable and then check for it inside of the view?
//controller.php
$this->view->setVar('options', $options);
//view.volt
{% if options['edit'] %}
{{ form.render('tax_categories_id')}}
{% endif %]
Just check if the element is exist
// add.volt
{% if form.has('tax_categories_id') %}
{{ form.render('tax_categories_id') }}
{% endif %}
Assuming you have crated something close to:
<?php
use Phalcon\Forms\Form,
Phalcon\Forms\Element\Text,
Phalcon\Forms\Element\Hidden;
class UsersForm extends Form
{
public function initialize($options = [])
{
if ( isset($options['edit']) && $options['edit'] ) {
$this->add(new Hidden('id'));
}
$this->add(new Text('name'));
}
}
So! Depending on options, you may have one field declared, or two instead. Now when someone sends you this form back, for validation you have to set it up again with proper $options['edit'], depending on if you have $_REQUEST['id'] declared or not:
$form = null;
if( isset($_REQUEST['id']) ) {
$form = new UsersForm();
} else {
$form = new UsersForm(['edit' => true]);
}
$form->bind($_REQUEST);
if($form->isValid()) {
//...
}
Quite an advanced (but with some gaps anyway) manual is here. Bet you were there already, but just in case.
Btw, form are iterators & traversables, so you can loop over them to render only elements, that are declared. Writing this because you have put {{ form.render('tax_categories_id')}} as an example and that makes me feel like you are generating fields by hand.
so I have a selection box that gives a dropdown menu to give messages a manager from the dropdown. It takes the input and then changes to a column in the database called manager for it's respective column. When I try to submit the selection menu it gives me the regular error for Laravel. But then when I put ?debug=1 at the end it submits but gives the row's manager column a value of just blank.
Here is what I have in the routes.php
Route::get('foo/{id}', 'fooController#bar');
Route::post('foo/{id}', 'fooController#bar');
This is the form.
{{ Form::open(array('url' => '/admin/foo' . $message->id)) }}
{{ Form::select('handler[]', array('unassigned', 'foo', 'bar'), null, array('style' => 'width: 127px')); }}
{{ Form::submit('Change manager') }}
{{ Form::close() }}
{{ $message->manager }}
and here is what is in the fooController
public function bar($id = null)
{
$message = Message::find($id);
$handler = Input::get('handler[]');
$message->manager = $handler;
$message->save();
return Redirect::action('AdminController#foo_bar');
}
I had a problem like this the other day, I have zero recollection of what I did. I really appreciate any help, thanks! The database is postgresql if that's any help
Try a dd(Input::all()) at the beginning of your controller and make sure you're seeing what you expect.
Also since you're sending an array perhaps you have to do Input::get('handler.0') -- see here right below the Input::only() and Input::except() code block.
It would seem as though because you are naming your select handler[], PHP is grabbing it as part of an array.
When setting up your message model, try this...
public function bar($id = null)
{
$message = Message::find($id);
$handler = Input::get('handler[]');
$message->manager = $handler[0];
$message->save();
return Redirect::action('AdminController#foo_bar');
}
Usually, you'd only use names in your forms post-fixed with [] when you are accepting multiple values like checkboxes/multi-selects etc... Otherwise, it's probably best to stick with not using it because it may cause confusion.
I managed to fix it in a almost frustratingly simple way by just changing the method to PUT.
like this
Form::open(array('url' => 'foo/bar', 'method' => 'put'))