I have a page to get some data from a user, this data will save in first_forms table, but I have other fields in the table for next page and they are null.
this is first_forms table :
In this table, project_name, customer_name, buyer, response, model will be saved in the first step in the first page choose.blade.php
This is store function in the controller:
FirstForm::create([
'model' => $request['model'],
'project_name' => $request['project_name'],
'customer_name' => $request['customer_name'],
'buyer' => $request['buyer'],
'response' => $request['response'],
]);
return view('Form2.firstForm');
As you can see other fields in first_forms table will be null. After this user redirect to next page firstForm. Now in this page users have to complete other fields like: airflow, tcp, compress_number, etc. I want when user click on submit in this page, new fields in this page save in the previous row in first_forms table who complete in the previous page, how can I do this?
I think I have to get the id of who completes he previous page and update row with new fields in a new page, but I don't know how I can get the id and update row. Primary key is id.
This is first_forms table when user complete first page :
This is the data of who completed the first page. On the next page, those fields are null, have to be complete in this row.
You can simply check that
$first = FirstForm::create([
'model' => $request['model'],
'project_name' => $request['project_name'],
'customer_name' => $request['customer_name'],
'buyer' => $request['buyer'],
'response' => $request['response'],
]);
//Below line will re-retrieve the record along with primary key which is `id`
$first = $first->fresh();
return view('Form2.firstForm',compact('first'));
In view you can access inserted data like $first->id Now place your id in a hidden field of the nextform and update your record according to that id. You can even show the previously inserted record in readonly fields of the nextform
In your nextform view
<input type="hidden" name="update_id" value="{{ $first->id ?? '' }}" />
When you submit the nextform with all other fields, you will get the hidden id as well. So again in your controller method you will do something like
FirstForm::where('id',request('update_id'))->update([
//here goes your other fields of the nextform
]);
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.
I have a form where I am adding some data to db, but I want to avoid duplicate records if user clicks multiple times on the button, I can disable the button using JS but I want to have some checking on server side as well.
Currently on form I am setting a session variable with random number and sending it to controller using textbox (hidden) and then in controller I check if session variable is equal to textbox then add to db - but still the data adds multiple time in db, would appreciate if someone could help. Thanks.
Controller:
if ($request->token == session('test')){
session()->forget('test');
sleep(20); (this i added in order to test)
TableName::create([
'code' => 'test',
'name' => 'testing',
]);
return "done";
} else {
return "stopped";
}
Blade:
{{session(['test'=> rand()])}}
<input type="text" value="{{session('test')}}" name="token">
There are two methods in Laravel firstOrCreate or firstOrNew.
Refer https://laravel.com/docs/5.8/eloquent
The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned
// Retrieve flight by name, or create it with the name, delayed, and arrival_time attributes...
$flight = App\Flight::firstOrCreate(
['name' => 'Flight 10'],
['delayed' => 1, 'arrival_time' => '11:30']
);
You can check with not exist in MYSQL, check Below
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;
I have a form generated using YII2 ActiveForm. there are some field I need to be on the if I select certain options , or need to have them removed if I select some other option.
For e.g. I Have a dropdown AccountType, with two options "individual" and "company".
If the user selects "individual" some fields on the form needs to go away say company name, and some other fields need to appear such as First name, last name. Initially when the display the form , only the Account Type field is there.
below is the code I have at the moment
<?php
$form = ActiveForm::begin(['id' => 'account-setup-form']); ?>
echo $form->field($modelAccMain, 'account_type')
->widget(Select2::classname(), [
'data' => $accountTypeArray,
'options' => ['placeholder' => 'Select account type'],
]);
echo $form->field($modelUsers, 'firstname')->textInput()
->hint('')->label('First Name');
echo $form->field($modelUsers, 'lastname')->textInput()
->hint('')->label('Last Name');
<?php ActiveForm::end(); ?>
Any help is greatly appreciated.
You can use scenarios for that, first define them in your model and than you can use a if statement in your view
if ($model->isAttributeActive('attribute_name')) {
But like #nterms wrote, if you want the user to be able to switch on the client side, javascript would be better.
Defining scenarios also helps with the validation (only active attributes will be validated).
p.s. Don't forget to set the scenario in your controller
$model = new MyModel(['scenario'=>'my_scenario']);
The way i would handle it is with jquery hide and show using the change event of the dropdown,
In your javascript
Assuming that the data in the select 2 widget is in the form of array
eg:
[1=>"first-item",2=>"second-item",...]
$(document).ready(function(){
var id= //check the id of the select2
on the inspect element id using chrome;
$("#id").on("change", function(){
if(id.value==1){
//show a div
}else{
//hide a div
}
//for multiple values better use switch
like this
switch(id){
case 1:{
$("#divid").show();
......
}
}
})
})
I hope you get the idea,
For the select 2 id you can set it via
echo $form->field($modelAccMain, 'account_type')
->widget(Select2::classname(), [
'data' => $accountTypeArray,
'options' => ['placeholder' => 'Select account type',"id"=>"mypreffereid"],
]);
I have a Product model with a 'categories' column. This column should be able to contain data from a Checkboxlist.
Whenever a user creates a new Product I want the form to display the 'categories' Checkbox, with the items set as active from the user's last created Product.
So for instance: the 'categories' Checkboxlist contains items 'Movies' and 'Music'. When the user checks 'Movies' and creates the Product, the next time the user goes to create a Product, 'Movies' is already selected (because it saves the selection from the user's previous product creation).
I believe these are the most effective steps to code in order to achieve this goal:
When Product is created: checked items are saved to 'categories' column in Product Model & a 'categories' column in the User's 'Profile' model
User's last saved categories ('categories' column in Profile model) should be retrieved at the Product's Create form.
Code in Product model's _form view:
<?php echo $form->checkBoxList($model, 'categories', array('movies'=>'Movies','music'=>'Music')); ?>
(I'm unsure as to where to set an array for active values)
I'll need to convert the Array of the selected Checkboxes to a string using explode(",", $model->categories) so I can put it inside the 'categories' columns of the 'Product' and 'Profile' models by using the ProductController's actionCreate function.
Then to set the user's last selected Checkboxlist items as active in the Product _form view I need to convert the $model->categories data back to an array by imploding the column ie implode(",", $user->profile->categories).
How would you code this in Yii?
Use CHtml::ckeckboxList instead of activecheckbox.
It have selected parameter. Selected there is array of key=>value pairs. yiiframework.com/doc/api/1.1/CHtml#checkBoxList-detail
Or you can rewrite (extend) you CHtml helper to resolve your format.
For example:
public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
if(array_key_exists('explode_format',$htmlOptions))
{
$selection=explode($model->$attribute);
unset($htmlOptions['explode_format']);
}
else{
$selection=self::resolveValue($model,$attribute);
}
if($model->hasErrors($attribute))
self::addErrorCss($htmlOptions);
$name=$htmlOptions['name'];
unset($htmlOptions['name']);
if(array_key_exists('uncheckValue',$htmlOptions))
{
$uncheck=$htmlOptions['uncheckValue'];
unset($htmlOptions['uncheckValue']);
}
else
$uncheck='';
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
$hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
}
Then just add 'explode_format'=>true to your htmloptions for activecheckboxlist. Something like this will work.
I have a small site which allows a user to enter values in a form and then either submit it directly or store the field values in a template to later submit it. To submit the form later, he can load the previously saved template. For that there are three buttons Load Template / Save Template / Submit form.
Because i am using the form validation built-in functionality from Codeigniter i run into problems when i want to populate the form with a template, which had been previously stored.
The form fields are all set up like
$name = array(
'name' => 'name',
'id' => 'name',
'value' => set_value('name', $form_field_values['name'])
);
The variable $form_field_values holds the values from either a loaded template in the case when a template has been loaded or the default values when the form is first loaded.
Initially the form is loaded with the default values. When i click on Load Template the values from the template are not chosen by set_value() because there were the default values in there before. What i want is to replace the values of the form fields with the ones from the template.
Do you have any idea how to do that in a clean approach? What i have done is to introduce a variable to skip the call to set_value() completely like:
$name= array(
'name' => 'name',
'id' => 'name',
'value' => $skip_form_validation ? $form_field_values['name'] : set_value('name', $form_field_values['name'])
);
Where $skip_form_validation is a variable set in the controller, based on what button was pressed. Form validation is skipped for saving/loading a template.
Codeigniter's set_value() function is a simple function which finds value in $_POST if value found then return else returns second argument, you can remove set_value() and write your own code for it. you can write $_POST['field_name'] if you want to populate value of POST data or add whatever value you want to add
Just use like this
$name = array(
'name' => 'name',
'id' => 'name',
'value' => $valueFromYourTemplate
);
You don't need to use set_value() function if you don't want to set POST values in the form
Assuming you retrieve the database fields and pass them to a data array in your controller.
$record = $this->data_model->get_record(array('uid' => $user_id), 'users');
if (!is_null($record)) {
$data['uname'] = $record->username;
$data['loc'] = $record->location;
}
where 'users' is the database table, and the uid is the id field of the table users.
In your form, do something like this
Hope it helps!