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.
Related
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 :)
I'm using select2 jquery plugin, and laravel form model binding to render the data from the server.
While everything else works fine, it doesn't rendered the tags that has been attached to the post as selected option.
there must be something which I'm unaware of, here's my view part.
<div class="form-group">
{!! Form::label('tag_list','Tags:') !!}
{!! Form::select('tag_list[]', $tags,null,['id'=>'tag_list', 'class'=>'form-control','multiple']) !!}
</div>
// This is the select 2 script
$('#tag_list').select2({
'placeholder':'Choose Tags',
tags:true,
tokenSeparators:[",", " "],
createTag:function(newTag){
return{
id:'new:' + newTag.term,
text:newTag.term + '(new)'
};
}
});
And this is a getTagListAtrribute function in Article model
// This is the getTagListAttribute function
public function getTagListAttribute(){
return $this->tags->lists('post_id')->all();
}
And I load the edit form from the controller like this:
public function article_edit($slug){
// fetch the articles.
//$article = DB::table('articles')->where('slug',$slug)->first();
$article = Article::where('slug',$slug)->first();
/*echo '<pre>';
print_r($article->title);
die();*/
$tags = DB::table('tags')->lists('name','tag_id');
$categories=DB::table('categories')->lists('category_name','category_id');
return view('admin.pages.edit', compact('article','tags','categories'));
}
I just want the tags which are associated with article be selected while the page loads, and which I've been unable of. So I'm in the need of help.
Well, since you have tagged the question as laravel-5.1. There are some changes been made to the lists method.
In Laravel 5.0.* it returned just the plain array of keys and/or values that you pass in the lists method. More info here
In Laravel 5.1.*, it returns a Collection object. More Info - Just the code documentation
So, the solution that you are looking for is:
In controller, do this:
$tags = DB::table('tags')->lists('name','tag_id')->toArray();
Or in the view file, do this:
{!! Form::select('tag_list[]', $tags->toArray(), null,['id'=>'tag_list', 'class'=>'form-control','multiple']) !!}
And that should do the trick for you.
EDIT 1:
Remove all() method from getTagsListAttribute(). That is not at all required.
Why are you using DB Facade for querying the tags table ? Since you have already established the relationship, you are unnecessarily executing the SQL Statements. Avoid that as much as you can.
You should get it by simply doing this:
$tags = $article->tags;
EDIT 2:
Are you sure that you have tag_id column in tags table ? I doubt that. I guess that must be a typo.. By mistakenly, you must have typed tag_id instead of id. Cross verify it for the confirmation.
Hope this helps you out. Happy Coding. Cheers.
Set select form tag like this
{!! Form::select('tag_list', $tags, $selected, ['id'=>'tag_list', 'name'=>'tag_list[]','class'=>'form-control','multiple']) !!}
Pass the ids to be selected as array in third ($selected).
So, if
$tags = ['1'=>'one', '2'=>'Two', '3'=>'Three']
and you want One and Three selected, pass these ids as an array to the form select as the third parameter.
so, $selected = [1,3];
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.
I am not able to redirect a custom form to specific action.
What I am trying is
<?= Html::submitButton( 'delete-selected' ,['class' => 'btn btn-primary']) ?>
here delete-selected is my custom action in controller appointment.
I have also tried like this:
public function actionDeleteForm()
{
return $this->render('delete');
return $this->redirect(['delete-selected']);
}
public function actionDeleteSelected()
{
Appointment::deleteAll(['doctor_name' =>4]);
return $this->redirect(['index']);
}
What I am trying to do is actually delete some records using the form. The form name is delete having a select drop-down field.
I want to post the data to action deleteselected and use the $_POST variable in the delete query.
How can I do this?
Thanks.
Any submit button that you put on your form will submit to the url specified in the action parameter of the form. If you haven't specified one, then Yii will use the current controller/action of the form. If you want to override this behavior, then you will need to specify an action for the form. e.g.
$form = ActiveForm::begin([
'action' => 'appointment/delete-selected'
]);
in actionDeleteForm you have
return $this->render('delete');
before
return $this->redirect(['delete-selected'])
this second instruction will never be executed because you have already made a return to the function and then control has already been returned to the caller
This is somewhat a note for Joe Miller's answer. If you are supposed to override the form's action with an action of a controller, make sure you make the value of 'action' as an array:
$form = ActiveForm::begin([
'action' => ['appointment/delete-selected']
]);
It will treat the action as a route to action delete-selected in controller appointment.
i am trying to populate two form fields from data that is retrieved from a database, in order for the user to update them. The table is called records and it is quite simple:
Record_ID
title
content
My model:
function get_data()
{
$r = $this->uri->segment(3);
$query = $this->db->get_where('records', array('Record_ID' => $r));
return $query->result();
}
My controller:
function set_values()
{
$data = $this->entries_model->get_data();
$this->load->view('update_view', $data);
}
and my update record view:
<?php
echo form_open('site/update',$data);?>
Title:
<?php echo form_input('title',set_value('title'));?>
Content:
<?php echo form_input('content',set_value('content'));
echo form_submit('submit', 'Submit');?>
<?php echo form_close();?>
The problem is that i get the following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/update_view.php
Line Number: 10
My question is twofold:
How do i access this data in my view form and
how do i populate the respective fields with it.
I am new to Codeigniter, my questions may look simplistic but any help would be appreciated. Thanks in advance.
There are a few things going on here:
$data is an array or object that is passed to a view. It's ELEMENTS are then available as variables in the view. So, $data['myelement'] = 'somevalue' in the controller would be accessed as $somevalue in the view.
If you pass a 2nd parameter to the form_open() method, it is expected to be a key/value pair of attributes for the tag that will be generated. like, array('class' => 'form_class', 'id' => 'form_id')
If you want to set the values of your form inputs, use the view helper function set_value(). In your case, use the controller to set elements in the $data array you'll pass to the view. $data['form_values'] = array('title' => $title, 'content' => $content);
Then, in the view:
You should pass a array to your view file. So replace:
$data = $this->entries_model->get_data();
with:
$data['entries_data'] = $this->entries_model->get_data();
and on your view file replace:
echo form_open('site/update',$data);?>
with:
echo form_open('site/update',$entries_data);?>
first you need to pass data in proper way
replace
$data = $this->entries_model->get_data();
with:
$data['data'] = $this->entries_model->get_data();
for setting value in set_value you need to do the in-line condition check to check either data is an object or not if object then put value other wise just empty
<?php echo form_input('title',set_value((is_object($data)?$data->title:'')));?>
you have to do the same thing for your all form fields
Jcory has answered your question but let me add a little to it.
In you model instead of return $query->result(); do this return $query->row(); this is because using returning a return object requires that you should loop through the resultset in your view
Instead of $data = $this->entries_model->get_data(); do this $data['entry'] = $this->entries_model->get_data();
In your view do this <?php echo form_input('title',set_value('title',$entry->title));?>
I hope these changes may solve the problem