Array of values from the same radio button group - php

I'm making a website in Laravel where user needs to enter his pseudonym, and on the settings page he can add multiple pseudonyms with jQuery. When he clicks the plus button, a text field, radio button and minus fields are added.
Radio buttons are there to mark one of those nicknames as default.
Image: screenshot of how the inputs look like
How do I pass an array of values out of those radio buttons? ie, if I selected 3rd out of 4 pseudonyms to be default:
{'0' => null, '1' => null, '2' => '1', '3'=> null}
So I can merge this array into pseudonyms array to be like:
{'0' => {'0' => 'John Doe', '1' => null},
'1' => {'0' => 'John Smith', '1' => null},
'2' => {'0' => 'John Wayne', '1' => '1'},
'3' => {'0' => 'John X', '1' => null}}
Finally, I would save it like this, or some other method that would also check if already existent and then update, but that's not important right now:
foreach($pseudonyms as $pseudonym)
$user->pseudonyms()->create(['name' => $pseudonym[0], 'status' => $pseudonym[1]]);
I'm probably just inexperienced and don't know some html/php basics that will let me do that, but what can I do :)
Anyway, here's the Blade part where inputs are:
<div class="input_fields_wrap">
<div class="row">
<div class="col-md-8">
{!! Form::text('pseudonyms[]', null,['class' => 'form-control']) !!}
</div>
<div class="col-md-2">
{!! Form::radio('default[]', 1, null,['class' => 'form-control']) !!}
</div>
<div class="col-md-2">
{!! Form::button('<i class="fa fa-plus" aria-hidden="true"></i>',['class'=>'btn btn-default add_field']) !!}
</div>
</div>
</div>
And here is the part of jQuery that appends the additional fields in .input_fields_wrap
$(document).ready(function() {
var max_fields = 5; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap .row"); //Fields wrapper
var add_button = $(".add_field"); //Add button ID
var added_fields = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(added_fields < max_fields){ //max input box allowed
$(wrapper).append('<div class="added"><div class="col-md-8 class1"><input type="text" name="pseudonyms[]" class="form-control"/></div>' +
'<div class="col-md-2 class2" ><input type="radio" name="default[]" value="1" class="form-control"/></div>' +
'<div class="col-md-2 class3" ><input type="button" value="-" class="remove_field btn btn-default add_field fa fa-minus"></div></div>'); //add input box
added_fields++; //text box increment
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).closest('.added').remove();
added_fields--;
})
});
Thank you for your comments!

Of course, solution was working on something else, coming back and having an answer after 2 minutes thinking about it. Created new array with a key from the radio button's value, so I could merge it with the other array with
foreach($request->pseudonyms as $key => $value)
{
if(array_key_exists($key, $default))
{
$pseudonyms[$key] = array($value, $default[$key]);
} else {
$pseudonyms[$key] = array($value, null);
}
}

Related

Yii2 - radioList choosing bindend to two different fields

I have two radioList bindend to two different fields:
<div class="form-group row">
<div class="col-lg-5">
<?= $form->field($model, 'isGdo')->radioList([0 => 'No', 1 => 'Yes'])->label("Are you a distributor ?"); ?>
</div>
<div class="col-lg-5">
<?= $form->field($model, 'isProducer')->radioList([0 => 'No', 1 => 'Yes'])->label("Are you a producer?"); ?>
</div>
</div>
Now my aim is to refactor this and create a radioList with 3 options in which I can set both these properties.
I know that I can switching to a single field with 3 values, but there are a lot of checks in the program, so keeping these two fields separate could be better for me.
Create A radio 3 radio buttons for showing with same name.
isGdo and isProducer
kept as hidden input field .
Write jquery code on above radio button and set that value on input box on basis of selection of radio button.
echo $form->field($model, 'isGdo')->hiddenInput(['value'=>''])->label(false);
echo $form->field($model,'isProducer')->hiddenInput(['value'=>''])->label(false);
$form->field($model, 'publicattribute')->radioList([1 => 'yes', 0 => 'No'])->label('');
<script>
$(document).ready(function(){
$("input[type='button']").click(function(){
var radioValue = $("input[name='']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
**insert that value on your condition in the hidden input field**
}
});
});
</script>

Get the Old input of googleMap in update form

Am building a form that the user will be able to provide his information and also provide where he want the bus to pick him up , so am using google Map Api , so that he can provide coordinates , this is done .
but now in the update form i cant get the Coordinates values from User Object so that i can update them ,
this is the result of User::first() "dummy data btw"
{"id":1,"name":"Hady2","email":"Hady2#mtc.com","created_at":"2017-08-24 00:25:19","updated_at":"2017-08-24 00:25:19","MobileNo":"111111","Age":12,"Gender":2,"OrganizationId":1,"Location":"30.03914,31.081119","CheckInLocation":"30.4414,31.00019","CheckOutLocation":"30.02914,31.111119","BusId":1}
u will see up the coordinates variables , i want to use them so that they appear in their fields in the update form , and then i able to update them,
update form code :-
this is start form code :-
{!! Form::model($user,['route'=>['users.update',$user->id], 'method'=> 'PUT']) !!}
this a user name tag , to show u how i get the old value to the user name input
{!!Form::text('name','',array('required' => 'required', 'placeholder' => 'Name', 'class'=>'form-control'))!!}-->
{!! Form::text('name',$user->name, [
'class' => 'form-control',
'placeholder' => 'Name',
'required',
'id' => 'name',
'data-parsley-required-message' => 'Name is required',
'data-parsley-trigger' => 'change focusout'
]) !!}
notice $user->name
the problem is i cant retrieve coordinates variables and put there values in the field of the update form so when i use $user->location or $user->CheckInLocation ,as u can see in the object above , it bring me nothing ,
image show the form update coordinates fields
this is the tag for coordiantes field in update form :-
<div class="form-group">
<label class="control-label col-md-2" for="Locations">Locations</label>
<div class="col-md-10">
<button id="stop_btn" disabled="disabled" class="btn btn-default" onclick="locationClick(); this.disabled = 'disabled';">Location</button>
<button id="pick_btn" class="btn btn-info" onclick="pickClick(); this.disabled = 'disabled';">Pickup Location</button>
<button id="drop_btn" class="btn btn-danger" onclick="dropClick(); this.disabled = 'disabled'; {{ $user->CheckOutLocation }}">Dropoff Location</button>
<div id="map" value="{{ $user->CheckOutLocation }}"></div>
</div>
</div>
so can any one help me to figure how can i make old values of coordintes appear in their fields of update form , thanks in advance , i hope every thing is clear.

Save multiple rows to database from dynamic forms in Laravel 5

I'm using jQuery to generate two dynamic fields. Each pair of fields is displayed on the page and can have multiple instances. On submit (not ajax), each pair of fields is saved into the their own table row along with Auth::id().
There are two forms in the HTML code, both values are entered, user clicks 'Add link' then jQuery creates two hidden fields (these are the ones that get submitted) and data entered appears (appended) visually to #link-list. The original fields become empty and the process can repeat...
I'm struggling to create an array that is recognised by eloquent to save the data multiple times.
I get the error 'Undefined index: link' or whichever the second input row is in jQuery.
Blade/HTML:
{!! Form::open(['route' => ['multiple.store'], 'method' => 'post', 'role'=> 'form', 'class' => 'form']) !!}
<ul id="link-list">
<!-- append new rows -->
</ul>
<div id="newlink" class="form-inline">
<div class="form-group">
{!! Form::text('prestore', null, ['placeholder' => 'Store name', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::text('prelink', null, ['placeholder' => 'Link / URL', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
<button class="btn btn-primary submit new-row" type="button">Add store link</button>
</div>
</div>
<br/><br/>
{!! Form::submit('Submit rows', ['class' => 'btn btn-success submit']) !!}
{!! Form::close() !!}
jQuery/JavaScript
$(document).on('click', '.new-row', function() {
var store = $('#newlink input[name=prestore]').val();
var link = $('#newlink input[name=prelink]').val();
console.log(store, link);
$('<li class="not-saved">' +
''+store+'' +
'<input type="hidden" name="rows[][link]" value="' + link + '">' +
'<input type="hidden" name="rows[][store]" value="' + store + '">' +
'</li>').appendTo('#link-list').hide().fadeIn(280);
$('input[name=prestore]').val('');
$('input[name=prelink]').val('');
});
Controller:
public function store()
{
$input = Input::all();
foreach ($input['rows'] as $row) {
$items = new Multiple([
'user_id' => Auth::id(),
'store' => $row['store'],
'link' => $row['link'],
]);
$items->save();
}
}
One problem is in your JavaScript element names:
<input type="hidden" name="rows[][link]" value="' + link + '">
<input type="hidden" name="rows[][store]" value="' + store + '">
This will generate $rows like:
[
0 => ["link" => "foo"],
1 => ["store" => "bar"]
]
But your PHP code expects $rows to be like:
[
0 => [
"link" => "foo",
"store" => "bar"
],
1 => [
"link" => "foo",
"store" => "bar"
]
]
One way to generate the expected values is to specify the row keys in your elements:
<input type="hidden" name="rows[0][link]" value="' + link + '">
<input type="hidden" name="rows[0][store]" value="' + store + '">
<input type="hidden" name="rows[1][link]" value="' + link + '">
<input type="hidden" name="rows[1][store]" value="' + store + '">
Obviously this is a bit tricky given the code you've provided, so let me know if you need assistance with that.
If this helps anyone else, this is the jQuery required to work with Ben's correct answer:
var count = 0;
$(document).on('click', '.new-row', function() {
count++;
var store = $('#newlink input[name=prestore]').val();
var link = $('#newlink input[name=prelink]').val();
if ($('input[name=prestore]').val().length > 2 && $('input[name=prelink]').val().length > 2) {
$('<li class="not-saved">' +
'' + store + '' +
'<input type="hidden" name="rows[' + count + '][store]" value="' + store + '">' +
'<input type="hidden" name="rows[' + count + '][link]" value="' + link + '">' +
'</li>').appendTo('#link-list').hide().fadeIn(280);
$('input[name=prestore]').val('');
$('input[name=prelink]').val('');
} else {
console.log('At least 3 characters for each field required!');
}
});
I also added a tiny bit of validation so it wont append empty fields
I agree that this is a problem with your element names, but disagree with Ben's solution. You can keep your JavaScript as-is and handle this in PHP:
public function store()
{
$rows = Input::get('rows');
$userId = Auth::id();
for ($i = 0; $i < (count($rows) - 1); $i += 2) {
$item = new Multiple([
'user_id' => $userId,
'link' => $rows[$i]['link'],
'store' => $rows[$i + 1]['store'],
]);
$item->save();
}
}

Prevent from submiting form several times by clicking fast in laravel

So I ran into issue, that If i click fast enough subnmit button, my form is submited several times. How can I prevent this? Token is added automatically, but it doesnt help at all I guess.
Form example:
<div class="row padding-10">
{!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}
<div class="form-group">
{!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="col-md-offset-5 col-md-3">
{!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
My NewsController store method:
public function store()
{
$validator = Validator::make($data = Input::all(), array(
'title' => 'required|min:8',
'body' => 'required|min:8',
));
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
News::create($data);
return Redirect::to('/news');
}
One approach is to use a click handler for the button where it first disables the button, then submits the form.
<script>
function submitForm(btn) {
// disable the button
btn.disabled = true;
// submit the form
btn.form.submit();
}
</script>
<input id="submitButton" type="button" value="Submit" onclick="submitForm(this);" />
Use PHP sessions to set a session variable (for example $_SESSION['posttimer']) to the current timestamp on post. Before actually processing the form in PHP, check if the $_SESSION['posttimer'] variable exists and check for a certain timestamp difference (IE: 2 seconds). This way, you can easily filter out multiple submits.
// form.html
<form action="foo.php" method="post">
<input type="text" name="bar" />
<input type="submit" value="Save">
</form>
// foo.php
if (isset($_POST) && !empty($_POST))
{
if (isset($_SESSION['posttimer']))
{
if ( (time() - $_SESSION['posttimer']) <= 2)
{
// less then 2 seconds since last post
}
else
{
// more than 2 seconds since last post
}
}
$_SESSION['posttimer'] = time();
}
Original POST
How to prevent multiple inserts when submitting a form in PHP?
Want to submit value of button as well and prevent double form submit?
If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.
// Add class disableonsubmit to your form
$(document).ready(function () {
$('form.disableonsubmit').submit(function(e) {
if ($(this).data('submitted') === true) {
// Form is already submitted
console.log('Form is already submitted, waiting response.');
// Stop form from submitting again
e.preventDefault();
} else {
// Set the data-submitted attribute to true for record
$(this).data('submitted', true);
}
});
});
Step 1: write a class name in the form tag Exp: "from-prevent-multiple-submits"
<form class="pt-4 from-prevent-multiple-submits" action="{{ route('messages.store') }}" method="POST">
#csrf
Step 2: write a class in button section
<button type="submit" id="submit" class="btn btn-primary from-prevent-multiple-submits">{{ translate('Send') }}</button>
Step 3: write this script code
(function(){
$('.from-prevent-multiple-submits').on('submit', function(){
$('.from-prevent-multiple-submits').attr('disabled','true');
})
})();

PHP Laravel - how to test if a checkbox is checked, if the value is a variable?

I'm a noob in Laravel, so please bear with me.
I'm continuing work on a friend's webpage that displays a list of items (with a checkbox beside each item). There are plenty of ways to interact with said items, such as "Delete", "Update", and the one I'm working on, "Download". There's a delete button per row/item/checkbox, so that a user can easily delete just one item. There's also a mass delete option, where the user can check multiple rows, check a "Delete" checkbox, and click on "Update". The webpage stores data on mongodb.
Supposedly, a user checks the box, clicks on Download, and a file is created and downloaded for the user.
But I'm not getting to that part yet. For now I'm having trouble even checking if the checkboxes are checked.
Here's my code:
Download Button:
<div class="col-md-1 col-md-offset-1">
{{ Form::open( array(
'url' => 'contents/download',
'role' => 'form',
'method' => 'POST',
'class' => 'form-inline'
)
) }}
<div class="form-inline" role="form">
<div class="form-group">
<input type="submit" class="btn btn-success" name="download" id="download" value="Download Selected">
</div>
</div>
{{ Form::close() }}
</div>
Here's the rows of checkboxes/items. Notice that the value of the checkbox is a variable - it corresponds to the ID of the item in the database.
#foreach($children as $child)
#if($mother->id == $child->mother_id)
<tr>
<td class="text-center">
{{--*/ $child->id /*--}}
<input type="checkbox" class="child" value="{{ $child->id }}" onclick=isSelected(this)>
</td>
<td>
<span class="glyphicon glyphicon-file"></span>
{{ ucwords($child->child) }}
</td>
<td class="text-center">
Coder
</td>
<td class="text-center">
{{ $child->updated_at }}
</td>
<td class="text-center">
{{ Form::open(array(
'url' => 'contents/delete',
'role' => 'form',
'method' => 'POST',
'class' => 'form-inline'
)
) }}
<input type="hidden" value="{{ $child->id }}" name="id">
<input type="submit" class="btn btn-danger btn-xs" name="deleteChild" value="Delete" onclick="return confirmDelete();" />
{{ Form::close() }}
</td>
</tr>
#endif
#endforeach
Controller Code:
public function postDownload()
{
$input = Input::all();
if(Input::has("child"))
{
echo $input["child"];
// Begin download
}
else
{
echo "none";
// Error - No Item selected
}
}
My understanding of Laravel is basic at best. Where did I go wrong? Or perhaps there's another approach to this?
First of all, in HTML you should give your checkboxes a name, perhaps something like items.
When you submit the form, Laravel get those data. And now if retrieve input by using Input::get('items'),
$itemIds = Input::get('items');
you will get an array whose elements are those checkboxes that were checked. This array is basically an indexed array, the structure could be like this
array(
[0] => '1', // item 1 ID
[1] => '5', // item 5 ID
[2] => '33' // item 33 ID
)
Finally, you are ready to process $itemIds however you want.
By the way, if no boxes were checked in your UI, you cannot get an array by calling Input::get('items'). Therefore, it might be better to check whether this field exists first by calling Input::has('items').
In your HTML , name the checkboxes dynamically after your item IDs.
Example , item1 , item2 etc.
Then check for selected items like this in your controller
$items = Item::all();
foreach($items as $item)
{
if($request->has('item'.$item->id)){
// item has been ticked
}
else{
// item was not ticked
}
}

Categories