I have a checkboxes like this:
<div class="form-group">
<div style="display:none ;" class="weekday_message form-control alert-warning"></div>
<label id="weekday2" for="weekday" class="col-md-4 control-label">Weekday</label>
<div class="required form-field" name="weekday" id="weekday">
<input class="weekday" type="checkbox" name="weekdays[]" value="MO">Monday
<input class="weekday" type="checkbox" name="weekdays[]" value="TU">Tuesday
<input class="weekday" type="checkbox" name="weekdays[]" value="WE">Wednesday
<input class="weekday" type="checkbox" name="weekdays[]" value="TH">Thursday
<input class="weekday" type="checkbox" name="weekdays[]" value="FR">Friday
<input class="weekday" type="checkbox" name="weekdays[]" value="SA">Saturday
<input class="weekday" type="checkbox" name="weekdays[]" value="SU">Sunday
</div>
<span class="help-block">
<strong></strong>
</span>
</div>
My validation:
public function rules()
{
return [
'startdate' => 'required|date',
'endate' => 'nullable|date',
'startime' => ['required', new Time],
'endtime' => ['required', new Time],
'title' => 'required',
'entity_id' => 'required',
'type' => 'required|exists:entities,type',
'description' => 'required',
'frequency' => 'required',
'interval' => 'nullable|numeric',
'monthday' => 'nullable|numeric|min:1|max:3',
'weekdays' => 'array|max:3',
'month' => 'nullable|numeric',
'until' => 'nullable|date',
'tags' => 'nullable',
];
}
and controller:
public function storeEvent(EventRequest $request)
{
$test = ($request->input('weekdays'));
dd($test);
$weekday_string = implode(",", $request->input('weekdays'));
$request->merge(array('weekday', $weekday_string));
dd($request->all());
$event = DirtyEvent::create($request->all());
$geoloc_id = Entity::find($event->entity_id)
->first();
$user_id = Auth::id();
// Save Geoloc + user id into newly created event
$event->_geoloc()->associate($geoloc_id);
$event->users()->associate($user_id);
$event->save();
Now, validation seems to pass because it does data dump, however both dd($test) as well as $request->all() are giving me back empty weekdays, like it would not be defined. What could be the possible cause of this?
If you want to make sure you have always at least one weekday selected you should change:
'weekdays' => 'array|max:3',
into:
'weekdays' => 'array|required|max:3',
Also I suppose you don't send data using standard HTML form because you set for example name for divs so maybe you forget to attach weekdays or have bug in code elsewhere?
Your HTML says weekday (singular) but your rules set says weekdays (plural).
There needs to be at least one checkbox selected to make the input weekdays to be included in the request. You can use a default value in case none was selected by adding a hidden input before the checkboxes.
<input type="hidden" name="weekdays" value="defaultValue">
Related
I need to save an array generated when I select several input type checkboxes, and I don't know how to do it Laravel Livewire. So, in this section, I select the checkboxes and send them by wire "documentos."
<input wire:model.defer="documentos" name="documentos" type="checkbox" value="Acta"
class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded">
<label for="acta" class="form-check-label">Acta</label>
<br></br>
<input wire:model.defer="documentos" name="documentos" type="checkbox" value="Documento Ideas"
class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded">
<label for="ideas" class="form-check-label">Documento Ideas</label>
<input wire:model.defer="documentos" name="documentos" type="checkbox" value="Plan Inversion"
class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded">
<label for="plan" class="form-check-label">Plan Inversion</label>
</div>
I have the save function in this section, but it only saves one value.
public function guardar()
{
$data = [
['id' => $this->use_id],
[
'tarea_paso' => $this->tarea_paso,
'descripcion_paso' => $this->descripcion_paso,
'fecha_inicio' => $this->fecha_inicio,
'fecha_fin' => $this->fecha_fin,
'id_responsable' => $this->id_responsable,
'documentos' => $this->documentos,
'acta' => $this->acta,
'ideas' => $this->ideas,
'plan' => $this->plan,
'acciones' => $this->acciones,
'poais_id' => $this->metodologia_id,
]
];
}
try this
$data = [
'tarea_paso' => $this->tarea_paso,
'descripcion_paso' => $this->descripcion_paso,
'fecha_inicio' => $this->fecha_inicio,
'fecha_fin' => $this->fecha_fin,
'id_responsable' => $this->id_responsable,
'documentos' => $this->documentos,
'acta' => $this->acta,
'ideas' => $this->ideas,
'plan' => $this->plan,
'acciones' => $this->acciones,
'poais_id' => $this->metodologia_id,
];
Model::where('id', $this->use_id)->update($data);
How will I validate the current entries from here , this is the json response inside the Chrome Devtools after submitting the form thru axios ?
And this is in my UpdateProfileRequest.php
public function rules()
{
return [
'username' => 'required|unique:users|min:3',
'password' => 'required|min:8|confirmed',
'confirm_password' => 'required|',
'current_password' => 'required|u',
'country_id' => 'required|integer',
'display_name' => 'required|min:5',
'email' => 'required|unique:users,email_address',
'phone_number' => 'required|alpha_num',
'image' => 'mimes:jpg,png,gif'
];
This is the whole response from the request
This is inside my UpdateProfile.vue
<div>
<div v-if="user != null">
<form class="bg-white m-auto h-full p-4 w-full" id="setup-billing-form" #submit.prevent="submitProfile()" method="POST">
<div class="flex inline-block">
<div id="input-group" class="w-3/5">
<label for="name" class="block uppercase tracking-wide text-black-v2 text-xs font-bold mb-2">Username
</label>
<input v-model="form.username" type="text" class="hover:bg-grey-lightest bg-grey-lighter w-full mb-2 p-2 leading-normal" id="pin" name="pin" autocomplete="name" placeholder="Your Username" required>
</div>
<div id="input-group" class="ml-2 w-3/5">
<label for="name" class="block uppercase tracking-wide text-black-v2 text-xs font-bold mb-2">Email
</label>
this is is inside my axios request
submitProfile(){
let data = new FormData();
axios.put(this.endpoint, {
form : this.form ,
image : this.image
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
},
Now, I want to ask if how do I validate those requests inside my UpdateProfileRequest, should I add the form. to each of those requests ?
Two Methods:
1. just use form.username to validate
$rule = [
'form.username' => 'required|unique:users|min:3',
'form.password' => 'required|min:8|confirmed',
'form.confirm_password' => 'required|',
'form.current_password' => 'required|u',
'form.country_id' => 'required|integer',
'form.display_name' => 'required|min:5',
'form.email' => 'required|unique:users,email_address',
'form.phone_number' => 'required|alpha_num',
'image' => 'mimes:jpg,png,gif'
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
}
2. Flatten the object to request:
It seems that you new a formdata without using it.
And pass the data with keys form and image.
You need to flatten your object before put it:
submitProfile(){
// if you use formdata
// let form = new FormData(this.form);
// let form = form.append('image', this.image);
let form = Object.assign({}, this.form); // clone this.form
form['image'] = this.image;
axios.put(this.endpoint, form).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
},
This request that you can directly validate by
'username', 'password', ... without prefix form.
and if you want to insert the datas, you can just use $request->except('image').
I have this code to store a conference. There is a form field that is for the user to select the available payment methods. The form field is like this:
<div class="form-group">
<label for="inputName">
Select the payment methods</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="payment_mb" id="payment_mb">
<label class="form-check-label" for="exampleRadios1">
MB
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="payment_c" id="payment_c">
<label class="form-check-label" for="exampleRadios1">
Credit Card
</label>
</div>
</div>
The code to store is like below.
But it shows an error:
SQLSTATE[HY000]: General error: 1366 Incorrect integer value:
'on' for column 'payment_mb' at row 1 (SQL:
insert into `conferences` (`name`, `organizer_id`,
`organizer_name`, `organizer_email`, `invoice_entity`,
`payment_mb`, `updated_at`, `created_at`)
values (a, 2, John W, emailtest#test.com, 1,
on, 2018-07-25 19:17:26, 2018-07-25 19:17:26))
Do you know why?
public function store(Request $request)
{
$conference = Conference::create([
'name' => $request->name,
'city' => $request->city,
'organizer_id' => Auth::id(),
'organizer_name' => $request->organizer_name,
'organizer_email' => $request->organizer_email,
'payment_mb' =>$request->payment_mb ? : 0,
'payment_c' => $request->payment_c ? : 0
]);
$conference->categories()->attach($request->categories);
$conference->save();
Session::flash('success', 'conference created.');
}
The $request->all() shows like:
array:25 [▼
"_token" => ""
"name" => "test"
"organizer_name" => "John W"
"organizer_email" => "..."
"payment_mb" => "on"
"payment_c" => "on"
"invoice_issuer" => "1"
]
Well on wouldn't be an int value. Your request has the value 'on' for that field.
'payment_mb' =>$request->payment_mb ? : 0,
You could maybe try:
'payment_mb' => (int) boolval($request->payment_mb),
Or even just:
'payment_mb' => (bool) $request->payment_mb,
PHP Docs - boolval
You could also actually set a value for the checkbox to be a '1' or something like that.
Some validation might be good.
Update
I think i was looking for filter_var:
filter_var($thatInput, FILTER_VALIDATE_BOOLEAN);
// 'on' => true
// null => false
// 'off' => false
Are you sure this is the correct store code?
payment_c does not appear in the sql statement even though it was set in your code.
I'm wondering how to map form field to eloquent model. Thing is that form input field has different name than eloquent model.
This is what i have
Model
class Message extends Model
{
protected $fillable = [
'name', 'email', 'subject_id',
];
}
Form
<form action="{{ action('MessageController#store') }}" method="post">
<input id="name" name="name" type="text">
<input id="email" name="email" type="text">
<select id="subject" name="subject">
#foreach ($subjects as $subject)
<option value="{{ $subject->id }}">{{ $subject->title}}</option>
#endforeach
</select>
</form>
Controller
public function store(Request $request)
{
$message = $this->validate(request(), [
'name' => 'required',
'email' => 'required',
'subject' => 'required',
]);
Message::create($message);
}
Notice that form select field name is subject and Message model field is subject_id.
Is it possible to map these two fields in Message model?
I guess it's possible in controller with something like
Message::create([
'name' => $request->input('name');
'email' => $request->input('email');
'subject_id' => $request->input('subject');
]);
but that's not what i want.
I don't expect some code improvements or suggestions as i'm complete Laravel noob :)
You could add a mutator on the Message model.
public function setSubjectAttribute($value) {
$this->attributes['subject_id'] = $value;
}
That essentially tells eloquent there is a subject attribute on the model but under the hood you're modifying subject_id
Hello i want to reuse a form in codeigniter but problem is the update form is populated one the page has load. Here is a sample form.
<?php
$attributes = array('class' => 'form-horizontal', 'id' => 'addPersonnel');
echo form_open($form_submission, $attributes);
?>
<input type="text" name="name" value="<?php echo set_value('name')?"> >
<input type="text" name="rank" value="<?php echo set_value('rank')?"> >
<button type="submit" class="btn btn-primary">Save</button>
<?php echo form_close()?>
My problem here lies in the set_value() method of the form_validation class since it will have conflict with populating the form if updating.
In your controller update function add a condition like:
if ($this->input->server('REQUEST_METHOD') === 'POST') {
$this->_get_userinfo_form_fields();
} else {
$this->_get_userinfo_form_fields($user_data); //$user_data from database
}
For add function you can directly call - $this->_get_userinfo_form_fields();
Then declare a function as below:
protected function _get_userinfo_form_fields($user_data = array()) {
$this->data['rank'] = array(
'placeholder' => 'Rank',
'name' => 'rank',
'id' => 'rank',
'class' => '',
'value' => isset($user_data['rank']) ? $user_data['rank'] :set_value('rank',$this->input->post('rank',TRUE)),
'style' => '',
);
//Add rest of the fields here like the above one
}
In view file add code like:
<?php echo form_input($rank);?>