I have a form which will have dynamic value and it will check that property id and then save it to the database.
For example in my database there is a table with title having the id=1, type having the id=2, description having the id=3, and after the form is submitted it will check if the field is title or type or description and it will save it in database that is if it is title it will save value of field title with propertyid value 1.
<form method="post" action="something.php">
<input type="text" name="field[][title]" value="edison">
<input type="text" name="field[][type]" value="book">
<input type="text" name="field[][description]" value="some description">
</form>
it is not inputting normal array in php with using foreach, I am not understanding how to get the value inside the index of the array to check with the sql database, that is to check if the field[][title]" then title has id 1 and if the field is field[][description]" it will check the sql for the property id of description that is 3
You need to look at it in reverse.
You first need to query your database so that you have a mapping of which field associates with which ID.
Then, when your information is posted, you can iterate over that mapping, detect if they have been posted, and use them accordingly:
$mapping = loadFieldNamesToFieldId();
/*
mapping should look something like:
$mapping = [
'title' => 1,
'type' => 2
];
*/
foreach ($_POST as $field_name => $field_value) {
if (isset($mapping[$field_name]]) {
$id = $mapping[$field_name];
// at this point you know that the user submitted a field which
// had $field_value, and which ID it relates to in your database
}
}
At which point you can just format your form as so:
<input type="text" name="title" value="edison">
I found this answer and thought of posting this as this relates to the answer
foreach ($_POST as $param_name => $param_val)
{
echo "Param: $param_name; Value: $param_val<br />\n";
}
Related
Still new to laravel, learning how the $request interacts with create.
here is my form for two of my variables for context:
<form method="POST" id="postForm">
{{-- #csrf --}}
<input type="hidden" id="id_hidden" name="id" />
<div class="form-group">
<label for="title"> Title <span class="text-danger">*</span></label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="category_description"> Description <span class="text-danger">*</span></label>
<textarea name="category_description" id="category_description" class="form-control"></textarea>
</div>
</form>
controller:
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'category_description' => 'required',
]);
$post = HmsBbrCategory::create($request->all());
if(!is_null($post)) {
return response()->json(["status" => "success", "message" => "Success! post created.", "data" => $post]);
}
else {
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
}
}
model:
protected $table = 'hms_bbr_category';
protected $fillable = [
"category_id", "title", "category_description", "category_description_2"
];
my title and category_description is inserting fine with an auto incremented id column. What I am trying to do is just to add 2 columns: category_id and category_description_2 that just copies the value inserted by id and category_description
Question:
how does 'required' retrieve the data from the form? I would like to have the same data thats taken and adding it to my two new columns. I am aware that I cannot just simple add 'category_description_2' => 'required',because this won't get an existing data.
so basically
$id = id
$category_id = id
$title = title
$category_description = category_description
$category_description_2 = category_description
1
Here is my table for reference. This form was given to me and I want to understand to know more about Laravel, thanks for reading and I hope I can get some suggestions on what to add.
You are running ->validate([]) on the $request variable which takes all of the information that is laravel puts together during the post request. If you do
dd($request->all()); you will be able to see all of the data that is passed from the form that you can run different validate rules on.
If you would like to add other data into your $request variable in order to save it to your model, you can always just add it to the $request array like so: $request['variable_1'] = 'data for variable one' and so on
Since I see that you have category_id that you would like to reference in your saved record, I would suggest you create a relation in your HmsBbrCategory model and the parent model that category_id belongs to. This will help you keep the integrity of your database in tact.
As another option, you can structure your url in such a way that passes the category_id to your store method in the controller. You will then need to find that category id and make sure it exists and save it via the relation that you created:
public function store (Request $request, $category_id){
$main_category = Category:find($category_id); //make sure it exists
$new_record = $main_category->exampleRelation()->save($request->all());
if(!$new_record){
return failed save
}
return successful save message
}
By doing the above, it will automatically insert the category_id into your saved record.
As another alternative, you could create a hidden field in your form that references category_id and other fields that you would like to add to your record on save. However, keep in mind which "sensitive" information you would like the users to see if someone decide to view source on the browser window.
Ok first I have a "settings" table on my database in which I have the fields "name" and "value" its a configuration kind of table where the value could be anything from string to boolean values etc.
Now on my blade, I have a form with various inputs "texts" "selects" "checkboxes" etc. When submitting the form on the controller I run a foreach where for each attribute of the $request I store its key as the name and its value as its value on the database.
$agency_id = Auth::user()->agency->id;
$settings = AgencySettings::whereAgencyId($agency_id)->get();
foreach ($request->except('_token') as $key => $value)
{
$setting = $settings->where('name','=',$key)->first();
if (boolval($setting))
{
$setting->value = $value;
$setting->update();
}else{
$setting = new AgencySettings;
$setting->agency_id = $agency_id;
$setting->name = $key;
$setting->value = $value;
$setting->save();
}
}
All works well except the unchecked checkboxes which are not inside the $request.
I know I can handle them like so $request->has('name_of_checkbox') but because of the dynamic nature of the table on the database, I don't want to have hardcoded on my Controller the name of a specific setting.
My goal is that the code on my Controller will be the same regardless the number of different settings I will use on my frontend (maybe in the future there will be a need to add more).
So my question, is there a way to handle those checkboxes serverside without having to refer to them specifically, or a way to always return the value of the checkboxes to the server despite its state?
My first thought is to go with javascript and hidden inputs, but maybe there is a better way.
You could add a hidden field with the same name before every checkbox you want to receive, like :
<input type="hidden" name="checkbox-1" value="0" />
<input type="checkbox" name="checkbox-1" value="1" /> My checbox 1
That will send the hidden field with the 0 value when the field is unchecked and send the proper truthy value when it's checked.
NOTE: Just make sure you're adding the hidden field first so you'll receive just the checked one when the field is checked.
Other solution is to simply check if value for "checkbox-1" is set in post array.
So you will set default to 0 on your controller side and check if value exists instead of checking if it is 0 or 1.
(M.)
I'm using CodeIgniter and I have 2 questions:
How do I call result from model to name property in any form inputs?
How do I get the dynamic name property posted in Controller?
This is what I tried in my HTML:
<input type="text" name="saa_<?php echo $row1['Tube_No']; ?>" value="<?= $row1['Pin_No']; ?>">
And this is what I tried in my controller:
$data = array(
'SA_No' => $this->input->post('saa_.$row1'),
);
How do i get my form input name property get posted to controller.
First you need to get the value of $row1['Tube_No']
$valueDefinedWhenRenderingTheView = $row1['Tube_No'];
then you need to access it like this:
$data = array(
'SA_No' => $this->input->post('saa_' . $valueDefinedWhenRenderingTheView)
);
because, when your defining the input name to be the concatenation of "saa_" and the value of $row1['Tube_No'].
How to save dynamical fields to database the problem is i don't know the names of fields we have module the user will add fields with name dynamically and i will save that fields names in database when the user checks the form for example he added fields in posts form so i want to save that fields data to database.Here's my code
<form>
<input type="text" name="firstname" id="firstname">
<?php foreach($extrafields as $extrafields1 )
{
?>
<input type="<?php $extrafields1->type; ?>" name="<?php $extrafields1->name; ?>" id="<?php $extrafields1->id; ?>" <?php $extrafields1->extraparameters; ?>>
<?php
}
</form>
If you can't define the name of the columns in the database, you'll have to save the data as JSON. So you'd create a column on your model called extra_parameters that would be a text column. When you post the form data, you'd need to update the model something like this:
//remove the expected parameters so you only have the extra ones
$extraparams = $request->except(['firstname','...']);
$model->extra_parameters = $extraparams;
You should also cast the column to an array in your model. This allows you to set $model->extra_parameters using an array, and it will automatically convert it to JSON when saving to the DB. It also lets you use $model->extra_parameters['param_name'] to access the fields.
//in your model file
protected $casts = [
'extra_parameters' => 'array'
];
see the array casting section here for more: https://laravel.com/docs/master/eloquent-mutators#attribute-casting
My CI view consists of a grid and data is added dynamically to this grid.This is saved to a database when a save button is clicked..
Here is the screenshot of the view.
[IMG]http://i40.tinypic.com/16a7dhl.png[/IMG]
When I submit the form,Grid data is first stored in an array and then array elements are joined together with a seperator in between them into a string.This string is stored in a hidden textbox and is submitted along with the form.After submission,in the controller they are seperated again & stored in the database.I have read that this method is prone to error.
Is there a better way to send array of data in a table to the controller than the above method? I have used Jqxgrid.
Use the jqxGrid's "getrows" to get all records as an Array.
You can use an array for the names of the fields.
<input type="hidden" name="field_name[]" value="foo">
<input type="hidden" name="field_name[]" value="bar">
$post = $this->input->post();
extract($post);
foreach($field_name as $k => $v){
$this->db->insert('tablename', array('fieldname' => $v));
}