How to insert multiple text input data with checkbox in laravel? - laravel-9

Basically I want to insert into database the data according to input value. I have multiple checkbox and input field. When I store data only " A " then its working and others are null values. If I stored others with A then stored all the values. User can be check and input values any time and any number of check box.
Here are the code snippet,
<form action="">
<input type="checkbox" name="txt_check[]" id="">A
<label for="fname">Win1:</label>
<input type="text" id="fname" name="txt_win[]"><br><br>
<label for="fname">Win2:</label>
<input type="text" id="fname" name="txt_loss[]"><br><br>
<label for="fname">Win3:</label>
<input type="text" id="fname" name="txt_draw[]"><br><br>
<input type="checkbox" name="txt_check[]" id="">B
<label for="lname">Loss1:</label>
<input type="text" id="fname" name="txt_win[]"><br><br>
<label for="lname">Loss2:</label>
<input type="text" id="fname" name="txt_loss[]"><br><br>
<label for="lname">Loss3:</label>
<input type="text" id="fname" name="txt_draw[]"><br><br>
<input type="checkbox" name="txt_check[]" id="">C
<label for="lname">Draw1:</label>
<input type="text" id="fname" name="txt_win[]"><br><br>
<label for="lname">Draw2:</label>
<input type="text" id="fname" name="txt_loss[]"><br><br>
<label for="lname">Draw3:</label>
<input type="text" id="fname" name="txt_draw[]"><br><br>
<input type="submit" value="Submit">
</form>
Here is the Controller:
$win = $request->txt_win;
$loss = $request->txt_loss;
$draw = $request->txt_draw;
$checkValue = $request->txt_check ;
foreach $checkValue as $key => $value) {
$result[] = Model::create([
'checkValue' => $value,
'winning' => $win [$key],
'lost' => $loss [$key],
'draw' => $draw [$key],
]);
}
This code works well for the first insert but when I try to second insert then insert null value like this-
I want to insert into database this way,
checkval win loss draw
A 2 3 4
B 3 4 3
C 4 5 5
How can I do this. I need help. Advanced thanks.

Your code is missing a circular brace on the foreach loop.
Change this
foreach $checkValue as $key => $value) {
$result[] = Model::create([
'checkValue' => $value,
'winning' => $win [$key],
'lost' => $loss [$key],
'draw' => $draw [$key],
]);
}
to this
foreach ($checkValue as $key => $value) {
$result[] = Model::create([
'checkValue' => $value,
'winning' => $win [$key],
'lost' => $loss [$key],
'draw' => $draw [$key],
]);
}

Related

How to upload image file on codeigniter 3?

I've tried everything to code upload the image file but I still stuck and it keeps an error. It can't detect the data of the image file so it can't store to the database when I submitted the form. I saw every tutorial I've been searched and look into my code seems everything right but why it still keeps an error.
Controller
public function create()
{
if (!$this->session->userdata('user_logged')) {
redirect('Auth');
}
$data["title"] = "Form Create Blog";
$data["landingpage"] = false;
$data['content'] = 'component/admin/blog/blog_create';
$this->form_validation->set_rules('blogTitle', 'Title tidak boleh kosong', 'required|max_length[50]');
$this->form_validation->set_rules('blogHeaderImg', 'Header Image tidak boleh kosong', 'required');
$this->form_validation->set_rules('blogKeyword', 'Keyword tidak boleh kosong', 'required|max_length[50]');
$this->form_validation->set_rules('blogContent', 'Content tidak boleh kosong', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('index', $data);
} else {
$config['upload_path'] = realpath(APPPATH . '../assets/img/upload/blog/header_image');
$config['allowed_types'] = 'jpg|png|PNG';
$nmfile = time() . "_" . $_FILES['blogHeaderImg']['name'];
$config['file_name'] = $nmfile;
$this->load->library('upload', $config);
if (!$this->upload->do_upload("blogHeaderImg")) {
$error = array('error' => $this->upload->display_errors());
echo '<div class="alert alert-danger">' . $error['error'] . '</div>';
} else {
$data = array('upload_data' => $this->upload->data());
$header_image = $data['upload_data']['file_name'];
$this->M_Blog->storeBlogData($header_image);
print_r($_FILES['blogHeaderImg']);
$this->session->set_flashdata('flashAddBlog', 'Data berhasil <strong>ditambahkan</strong>');
redirect('blog');
}
}
}
Model
public function storeBlogData($header_image)
{
$data = [
'title' => $this->input->post('blogTitle', TRUE),
'header_image' => $header_image,
'content' => $this->input->post('blogContent', TRUE),
'blog_keyword' => $this->input->post('blogKeyword', TRUE),
'created_by' => $this->session->userdata('user_logged')->id,
'last_modified_by' => $this->session->userdata('user_logged')->id,
'is_deleted' => 'n'
];
$this->db->insert('blog', $data);
}
View
<form method="POST" action="create" enctype="multipart/form-data">
<div class="form-group">
<label for="blogTitle">Title</label>
<input class="form-control" type="text" name="blogTitle" id="blogTitle" placeholder="Title">
<small class="form-text text-danger"><?= form_error('blogTitle') ?></small>
</div>
<div class="form-group">
<label for="blogHeaderImg">Header Image</label>
<input class="form-control-file" type="file" id="blogHeaderImg" name="blogHeaderImg">
<small class="form-text text-danger"><?= form_error('blogHeaderImg') ?></small>
</div>
<div class="form-group">
<label for="blogKeyword">Keyword</label>
<input class="form-control" type="text" id="blogKeyword" name="blogKeyword" placeholder="Keyword">
<small class="form-text text-danger"><?= form_error('blogKeyword') ?></small>
</div>
<div class="form-group">
<label for="blogContent">Content</label>
<textarea class="form-control" type="text" id="blogContent" name="blogContent" placeholder="Content" rows="10"></textarea>
<small class="form-text text-danger"><?= form_error('blogContent') ?></small>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
already solved. I just have to add this code to blog controller
if (empty($_FILES['blogHeaderImg']['name'])) {
$this->form_validation->set_rules('blogHeaderImg', 'Document', 'required');
}
instead of using this code
$this->form_validation->set_rules('blogHeaderImg', 'Header Image tidak boleh kosong', 'required');
thank you

Laravel 5.7 Auth::attempt return false

Auth::attempt always return false , can't understand why .
web.php
Route::post('/login','SessionsController#store');
Route::post('/register','RegisterController#store');
RegisterController.php
public function store()
{
$this->validate(\request(),[
'name' => 'bail|required|min:3|max:30|string',
'email' => 'bail|required|email',
'password' => 'required|confirmed'
]);
$user = User::create(request(['name','email','password']));
$user->fill([
'password' => Hash::make(\request()->newPassword)
])->save();
auth()->login($user);
return redirect()->home();
}
SessionsController.php
public function store(Request $request)
{
$credentials = $request->only('email', 'password');
if (! Auth::attempt($credentials)) {
return back()->withErrors(['message'=>'Email and Password doesn\'t match']);
}
return redirect()->home();
}
create.blade.php (Login Page)
<form action="/login" method="post">
#csrf
<div class="form-group">
<label for="email" class="form-text">Email :</label>
<input type="email" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password" class="form-text" >Password :</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<input type="submit" class="btn btn-primary float-right" value="Register">
</form>
Every thing is okay with registration and database , passwords is hashed .
Auth::attempt always return false .
Can't understand why , posted it after few hours of searching .. most of code is just copied from documentation.
Thanks in advance.
just changing
$user = User::create(request(['name','email','password']));
$user->fill([
'password' => Hash::make(\request()->newPassword)
])->save();
to
$user = User::create([
'name' => request('name'),
'email' => request('email'),
'password' => bcrypt(request('password'))
]);

Aurelia Validation - one of two fields must be mandatory

<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">SKU</label>
<input disabled.bind="readonly" type="text" class="form-control" value.bind="production.Sku1">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">SKU</label>
<input disabled.bind="readonly" type="text" class="form-control" value.bind="production.Sku2">
</div>
</div>
</div>
I have the textboxes above, either sku1 must be mandatory or sku2. I know how to do this in what seems like everything but Aurelia.
I was hoping it would be something simple like
this.validator = this.validation.on(this)
.ensure('production.StockStatusId').isGreaterThan(0).withMessage('is required')
.ensure('production.Sku1').isNotEmpty().Or.ensure('production.Sku2').isNotEmpty();
I have touched on if statements but unsure what the computedFrom would be
UPDATE
I was hoping this would work, however it isn't. Anyone know why?
.ensure('production.Sku1', (config) => {config.computedFrom(['HasProvidedEitherSku'])})
.passes(() => { return this.HasProvidedEitherSku }).withMessage("(Need to provide a SKU)")
get HasProvidedEitherSku(){
if ((this.production.Sku1 === undefined || this.production.Sku1 === null) && (this.production.Sku2 === undefined || this.production.Sku2 === null)){
return false;
} else {
return true;
}
}
UPDATE
This does work, in a way. However both show the error straight away however the error is only cleared on the one that has become valid. I understand why as the error message is attached to each one sep, however I dont know how to stop this
.ensure('production.Sku1', (config) => {config.computedFrom(['HasProvidedEitherSku'])})
.if(() => { return this.HasProvidedEitherSku })
.isNotEmpty().withMessage('a SKU is required')
.endIf()
.ensure('production.Sku2', (config) => {config.computedFrom(['HasProvidedEitherSku'])})
.if(() => { return this.HasProvidedEitherSku })
.isNotEmpty().withMessage(‘a SKU is required')
.endIf();
Here is what I have used:
HTML
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">SKU</label>
<input disabled.bind="readonly" type="text" class="form-control" value.bind="Sku1">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label"> SKU</label>
<input disabled.bind="readonly" type="text" class="form-control" value.bind="Sku2">
</div>
</div>
Validation
.ensure('Sku1', (config) => {config.computedFrom(['Sku1, Sku2'])})
.if(() => { return this.HasProvidedEitherSku1OrSku2 === false })
.isNotEmpty().withMessage(‘at least one sku is required')
.hasLengthBetween(0, 50)
.endIf()
.ensure('Sku2', (config) => {config.computedFrom(['Sku1, Sku2'])})
.if(() => { return this.HasProvidedEitherSku1OrSku2 === false })
.isNotEmpty().withMessage(‘at least one sku is required’)
.hasLengthBetween(0, 50)
.endIf();
Validation Method
get HasProvidedEitherSku1OrSku2 (){
if ((this.Sku1 === undefined || this.Sku1 === null || this.Sku1 === '') && (this.Sku2=== undefined || this.Sku2=== null || this.Sku2=== '')){
return false;
} else {
return true;
}
}

how to set radio button checked in edit mode in MVC razor view

I am new in MVC razor. I am trying to edit the web page. In which I have two radio buttons. I am successful in save data for radio button values. But when I trying to edit that value I am not able to select that radio button for which data is saved.
I have enum for Gender
public enum Gender
{
Male,
Female
}
My create code is :-
<div class="editor-label">
#Html.LabelFor(model => model.gender)
</div>
<div class="editor-field">
#Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
#Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>
Edit code is like
<div class="editor-label">
#Html.LabelFor(model => model.gender)
</div>
<div>
#if (Model.gender == (int)Gender.Male)
{
#Html.RadioButtonFor(model => model.gender, "Male", new { #checked = true })
#Html.Label("Male")
#Html.RadioButtonFor(model => model.gender, "Female")
#Html.Label("Female")
}
else
{
#Html.RadioButtonFor(model => model.gender, "Male")
#Html.Label("Male")
#Html.RadioButtonFor(model => model.gender, "Female", new { #checked = true })
#Html.Label("Female")
}
</div>
You have written like
#Html.RadioButtonFor(model => model.gender, "Male", new { #checked = true }) and
#Html.RadioButtonFor(model => model.gender, "Female", new { #checked = true })
Here you have taken gender as a Enum type and you have written the value for the radio button as a string type- change "Male" to 0 and "Female" to 1.
Don't do this at the view level. Just set the default value to the property in your view model's constructor. Clean and simple. In your post-backs, your selected value will automatically populate the correct selection.
For example
public class MyViewModel
{
public MyViewModel()
{
Gender = "Male";
}
}
<table>
<tr>
<td><label>#Html.RadioButtonFor(i => i.Gender, "Male")Male</label></td>
<td><label>#Html.RadioButtonFor(i => i.Gender, "Female")Female</label></td>
</tr>
</table>
Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:
Controller:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
user.user_gender = collection["rdbtnGender"];
return RedirectToAction("Index");
}
catch(Exception e)
{
throw e;
}
}
public ActionResult Edit(int id)
{
CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
ViewBag.UserObj = user;
return View();
}
VIEW:
Create:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label for="rdbtnGender2">FEMALE</label>
Edit:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" #(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" #(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>
Here is how I do it and works both for create and edit:
//How to do it with enums
<div class="editor-field">
#Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
#Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>
//And with Booleans
<div class="editor-field">
#Html.RadioButtonFor(x => x.IsMale, true) Male
#Html.RadioButtonFor(x => x.IsMale, false) Female
</div>
the provided values (true and false) are the values that the engine will render as the values for the html element i.e.:
<input id="IsMale" type="radio" name="IsMale" value="True">
<input id="IsMale" type="radio" name="IsMale" value="False">
And the checked property is dependent on the Model.IsMale value.
Razor engine seems to internally match the set radio button value to your model value, if a proper from and to string convert exists for it.
So there is no need to add it as an html attribute in the helper method.
To set radio button checked in edit mode in MVC razor view, please trying as follow:
<div class="col-lg-11 col-md-11">
#Html.RadioButtonFor(m => m.Role, "1", Model.Role == 1 ? "checked" : string.Empty)
<span>Admin</span>
#Html.RadioButtonFor(m => m.Role, "0", Model.Role == 0 ? "checked" : string.Empty)
<span>User</span>
#Html.HiddenFor(m => m.Role)
</div>
Hope it help!
Add checked to both of your radio button. And then show/hide your desired one on document ready.
<div class="form-group">
<div class="mt-radio-inline" style="padding-left:15px;">
<label class="mt-radio mt-radio-outline">
Full Edition
<input type="radio" value="#((int)SelectEditionTypeEnum.FullEdition)" asp-for="SelectEditionType" checked>
<span></span>
</label>
<label class="mt-radio mt-radio-outline">
Select Modules
<input type="radio" value="#((int)SelectEditionTypeEnum.CustomEdition)" asp-for="SelectEditionType" checked>
<span></span>
</label>
</div>
</div>
In my case the #checked = "checked" attribute did not work because I was loading default values from the model, which were not equal with the RadioButton value.
Once I changed the loaded values from the model to be equal to the radiobutton value, the button was checked.
For example this will make the radiobutton to be checked by default:
In the model:
response.data = "data"
In the view:
#Html.RadioButtonFor(m => m.data, "data",new {#class="form-check-input"})
<label class="form-check-label">Data (default)</label>

How to get some forms from request?

So, I've this form in server side:
case class Employe(id: Int, name: String)
val myForm = Form(
mapping(
"id" -> number,
"name" -> text
) (Employe.apply) (Employe.unapply)
)
So, in client side I need send three same forms to the server:
<html>
<body>
<div class="employe">
<input type="number" class="employe_id"/>
<input type="text" class="employe_name"/>
</div>
<div class="employe">
<input type="number" class="employe_id"/>
<input type="text" class="employe_name"/>
</div>
<div class="employe">
<input type="number" class="employe_id"/>
<input type="text" class="employe_name"/>
</div>
<input type="button" id="send_button"/>
</body>
</html>
and this data I send to the server via ajax with following code:
var allEmployes = $('.employe');
var addUrl = '/employes/add';
var employesArray = [];
for(var i = 0; i < allEmployes.length; i++) {
var currentRow = $(allEmployes[i]);
var emplId = currentRow.find('.employe_id').val();
var emplName = currentRow.find('employe_name').val();
var employe = {
'id' : emplId,
'name': emplName
};
employesArray.push(employe);
}
$.post(addUrl, { 'employes': employesArray })
.done(function(response){
console.log(response);
})
.fail(function(error){
console.log(error);
});
but, I don't know how to get three same forms from request (in Action of Server side)? Anybody know how to can this?
Thanks in Advance!
In controller change form mapping as
val myForm = Form(
mapping(
"id" -> list(number),
"name" -> list(text)
) (Employe.apply) (Employe.unapply)
)
and in html
<div class="employe">
<input type="number" name="id[0]" />
<input type="text" name="name[0]" />
</div>
<div class="employe">
<input type="number" name="id[1]" />
<input type="text" name="name[1]" />
</div>
<div class="employe">
<input type="number" name="id[2]" />
<input type="text" name="name[2]" />
</div>