Codeigniter large form insertion - php

I've a form with 120 fields to insert into the DB. The form is inserting fine and the approach I used is below:
I'm fetching all the fields from the view as below in the controller and passing the array($postdata) to the model file to insert.
**View**
$postdata = array(
'firstname' => $this->input->post('firstname'), //1st field
'lastname' => $this->input->post('lastname'), // 2nd field
'age' => $this->input->post('age'),
....
....
'test' => $this->input->post('test') // 120th field.
);
$this->Form_Model->insertdata($postdata);
**Model:**
function insertdata($data = array()) {
$sql_query = $this->db->insert('form_insert', $data);
redirect('Form');
}
My question is Is there any better way to insert. This approach feels bit repetitive.

If you simply want to get an array of all the data submitted, you can do it like this:
$postdata = $this->input->post();
This means, all the data submitted from the form will be there in this array.
And if you want to remove any particular element from this array, you can use unset().
Say for example, you may have named your submit button as "submit_btn" like this:
<input type="submit" name="submit_btn" />
then this value would be there in the above returned array. You can remove it like this:
$postdata = $this->input->post();
unset( $postdata['submit_btn']);
Btw, I have a couple of suggestions. The logic part is done in a Controller(you referred it by mistake as View). A View is simply for the displaying. And the Model is for the database communication.
Also, it would always be better to do some validations on the input that you received from the User through form submissions. We may don't even know what data they are sending!
And move that redirect() you used in the Model to the Controller from where you were trying to call that insertdata() method. In that Model, you just return a value (true or false or maybe something else) and do the business logic inside the Controller
You were kind of mixing up everything. That's why I thought to give you some pointers to help you.
Hope it helps :)

Related

Get data from multiple forms Laravel

I am working on Laravel. I have a blade view page on which multiple forms (of same model) are created. Now, I want, that when I click submit button, an array of all the forms should be returned to controller. But, it returns data of only one form instead of array. How can I achieve this, Can anyone help me?
It's not a real Laravel issue.
The trick is using different forms with each a submit button. Then, it's simple. Check the submitted button.
if ($request->isMethod('post')) {
if ($request->has('submit_button_form_1')) {
// Handle form
}
elseif ($request->has('submit_button_form_2')) {
// Handle form
}
elseif ($request->has('submit_button_form_3')) {
// Handle form
}
}
First of all I dont think you can send multiple forms, that is just way it is.
You have two options.
First: Make one form with all fields from all forms, and then in controller you just take what field you want, just like you would do from arrays so same thing.
Like:
$all_fields= Request::all();
and then
$all_fields['something'], $all_fields['something_else'],
Second: Using ajax, you can manipulate and send values of fields, fields that you need.
What you can do is you need to loop the form field with naming structure as first_name1, first_name2 and so on. Then, after submitting the form, you can validate using the loop in the same way and get the values. You can check my sample code here. It count the number of loops to be made.
You can pass the counter from the view to the controller in hidden field. Then, you can loop for validation and for taking the inputs.
Check my sample code:
//determine number of rows in database
$number_of_loop = Input::get('number_of_loop');
$arrayList = []; //defining the array variable
//declaring the validations rules
for($i = 1; $i < $number_of_loop; $i++){
$rules = array(
'currency'.$i => 'required',
'iso_code'.$i => 'required',
'symbol'.$i => 'required',
'status'.$i => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::back()->withErrors($validator)->withInput();
}
}
for ($i=1; $i <= $number_of_loop; $i++) {
$new_currency = new stdClass();
$currency = Input::get('currency' . $i);
$iso_code = Input::get('iso_code'.$i);
$symbol = Input::get('symbol'.$i);
$conversion_rate = Input::get('conversion_rate'.$i);
$status = Input::get('status'.$i);
$new_currency->currency = $currency;
$new_currency->iso_code = $iso_code;
$new_currency->symbol = $symbol;
$new_currency->conversion_rate = $conversion_rate;
$new_currency->enable = $status;
array_push($arrayList, $new_currency);
}
Update1
For storing all the records, create an array and a new stdclass. Store all the variable in stdclass attributes. and at last, push the new stdclass to the array. Then, you can access all the inputs of form. Check above updated code sample
If you’re using Laravel 5.2 then you can validate array data. You’ll need to put all of your inputs in one form as you just can’t send multiple forms. If each form had different URLs for the action attribute, how would that work?
To send data as an array, you can suffix the name attribute with []:
{!! Form::open() !!}
{!! Form::text('name[]') !!}
{!! Form::text('name[]') !!}
{!! Form::text('name[]') !!}
{!! Form::close() !!}
When this form is submitted, name will be an array with three elements.
To validate, use a wildcard in your validation rule name:
return [
'name.*' => 'required|max:255',
];
You can then access the array of names in your controller through the Request object:
$names = $request->get('names', []);
foreach ($names as $name) {
User::create(['name' => $name]);
}
I don’t know your data structure as you haven’t included it in your question, but this should be enough for you to apply to your given scenario.

Keep checked value of Yii radiobuttonlist after submit

I'm using a radioButtonList like this one:
$form->radioButtonList(Store::model(), 'product',
array(CODE1 => TEXT1,
CODE2 => TEXT2,
CODE3 => TEXT3)
);
This radioButtonList is part of a form with more fields. After submiting, if any field is incorrect, I show some error message and populate the correct fields using $_POST.
All the fields get its previous values except this radioButtonList. I need to set checked the value of the radioButtonList which was selected before submit, but I can't find how to do it.
Create $model = new Store(); in your action, pass it to view and use $model variable instead Store::model(). This should help.
UPD: You need to use the same $model after validation.
You can use
CHtml::radioButtonList(string $name, string $select, array $data, array $htmlOptions=array ( ));
In Your case it will be
CHtml::radioButtonList('product',$_POST[product],array(CODE1 => TEXT1,CODE2 => TEXT2,CODE3 => TEXT3));
Finally, I got a solution. (not an elegant one, but it works)
From the view:
Store::model()->product = $_POST["Store"]["product"];
Right before display the radioButtonList

Undefined variable in select when submitting form in Laravel 4

I'm trying to pull data from a table, populate a select input with that data, then post that information (and other info) to another table. When the view is rendered, it correctly populates the select with the data required, however when I submit the form, I receive an undefined variable error.
Undefined variable: secondarygenre
View
{{ Form::select('genre', $secondarygenre, null, array('class' => 'form-control', 'id' => 'genre')) }}
Controller
//Data is passed to the form in the view
public function addSubmission() {
$secondarygenre = Genre::lists('friendlyName', 'id');
return View::make('add')
->with('secondarygenre', $secondarygenre);
}
//Form is submitted
public function successfulSubmission() {
$track = new Track();
$track->genre_id = Input::get('genre');
$track->save();
}
If it's populating the select input with data, I know that it's the variable is not undefined.
I apologise if I've missed something, this is my first project with Laravel (or any MVC framework).
Any help would be greatly appreciated!
In the post, you have to also return the view with the variable, it looks like you're only doing that with the get, but you need to use ->with('secondarygenre', $sg) once for each type of request.

Codeigniter - How to populate form from database?

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!

Zend Framework: Can I use an add view script for editing too?

I have a simple Zend Framework that has a view script to add records to the database. This is a silly question IMHO, but how can I use the add view script to edit the record as well??
I have played around with a few scenarios to no avail.
Thanks,
Steve
Per Matt S' comment, the method you're looking for is Zend_Form::populate(). There are some notes about it in the documentation: Populating and Retrieving Values.
Basically, you use it like this in the controller:
$form = new Form_Person();
// get the data from somewhere
if($id = $this->getRequest()->getParam('id') && $model->find($id)) {
// really, use data from the model here
// but the populate() -method can take any array as an argument
$form->populate(array(
'name' => 'Dolph',
'age' => '52'
));
}
$this->view->form = $form;
and in your view, as usual:
<?= $this->form ?>
So the array could be for example the result of Zend_Db_Table_Row_Abstract::toArray() with column names matching to the names you gave the form elements.

Categories