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];
Related
Is it possible to make an API which prints database records like this: http://localhost:8000/products/?compare=1-2-N...(1,2,N) product id's. I have succeeded printing only one record. My route:
$router->get('products/{id}','ProductController#getProduct');
and my controller:
public function getProduct($id){
$tlt_products = DB::table('tlt_products')->find($id);
$tlt_products_features_id = DB::table('tlt_product_features')->where('product_id', $id)->get()->pluck('feature_id');
$tlt_features = DB::table('tlt_features')->whereIn('id', $tlt_products_features_id)->get()->groupBy('feature_group');
$tlt_feature_groups = DB::table('tlt_features')->groupBy('feature_group')->get()->toArray();
return response()->json([
'product' => $tlt_products,
'product_features' => $tlt_features,
'feature_groups' => $tlt_feature_groups
]);
}
could you please help me printing array of records using route like this:
http://localhost:8000/products/?compare=1-2-3...-N
Yes, it can be possible. You can try to pass a pattern through get and parse it to retrieve the information your need, but why don't you use a simple way to do that such as:
$router->get('products/{begin}/{end}','ProductController#getProduct');
every thing you want it possible just design it well and in your controller, you have
public function getProduct($begin,$end){
...
}
I finally managed to solve this issue using $tail = $request->tail;method and adding requested id like this on my form action
#php
$tail = basename(request()->path());
$text = (string)$tail;
#endphp
<form action="/product-compare/{{$text}}-{{ $product['id'] }}" method="post">
Merry Christmas to you all. Hope we are all having a wonderful time? I'm sure my guess is right. Could someone help me out on this? I don't know why this code returns the id as the value when binding to a select box. All I want to do is to bind a record of MySQL DB to a select box. Though, it is smooth when not using a where clause,
This is the controller:
public function create()
{
$listCompanies = Company::where('user_id', '=', Auth::user()->id)->orderBy('companyname', 'desc')->lists('companyname', 'id')->toArray();
return view('product.create')->with('listCompanies', $listCompanies);
}
This is the view:
<p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies) !!} </p>
When I checked the returned source page I found this:
<p><select name="companyname"><option value="" selected="selected">Select a Company</option><option value="1">New Company Nigeria</option><option value="2">Latest Company Nigeria</option></select> </p>
When I select a value from the selectbox, it returns the id, ie, 1, and that is what it adds to the DB not the actual value.
See the attached image for clarification. Please, your input is highly needed.
The option value is what gets saved. If you just want the names, use lists('companyName', 'companyName')
But typically you do want the id in your foreign key field. How do you have the relationship set up?
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.
I’m trying to implement a simple search into an application, but not sure of the best way to handle this. My database contains a Listings object which includes City field. I want to create a search form where the user inputs a city into a text field and gets all of the Listings for that city on the next page. I don’t want to perform a full-text search, just the query on that City field.
Also, on the results page, I’d like to store the query in POST and can’t figure out the best way to do this.
What is the best way to approach this in the controller?
Well your view would look something like this
$this->Form->Create('Listing', array('action'=>'search'));
$this->Form->input('city', array('default'=>$city));
$this->Form->end();
if (isset($listings)) {
//code to display listings
}
This view would create the correct form. And your controller needs to get that value
function search() {
$city = '';
if (!empty($this->data)) {
$city = $this->data['Listing']['city'];
$opts = array(
'conditions' => array('Listing.city' => $city)
);
$listings = $this->Listing->find('all', $opts);
$this->set('listings', $listings);
}
$this->set('city', $city); // so the keyword is saved. Can also get it via $this->data
}
This code should give you an idea on how to do this.
This is a great tutorial with a CakePHP search plugin tutorial. You can download the full working code as well from github (w/ MySQL dump).
View:
<?php echo $this->Form->create()
echo $this->Form->input('search');
?>
<input name="data[Product][word]" />
controller:
<?php
$result = $this->Product->find('all',array(
'conditions'=>array(
'OR'=>array(
array('name LIKE'=>'%'.$word.'%'),
array('description LIKE'=>'%'.$word.'%')))));
$this->set(compact('result'));
?>
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.