How to obtain the values of a select element with multiple attribute using jinput? - joomla

I'm trying to get the values ​​of a select element that has the multiple attribute using jInput. I estimate to obtain a series of values ​​but only obtain the value of the last selected option
The definition of the select is as follows
... other inputs ...
<select name="jform[something]" id="something" multiple>
<option value="A">A</option>
<option value="B">B</option>
<option value="...">...</option>
<option value="Z">Z</option>
</select>
In the controller I have the following logic that obtains the values ​​of the inputs including the select.
$requestData = $this->input->post->get('jform', array(), 'array');
Here I hope that the value of the select is a series of selected values ​​but as I mentioned before I get only the value of the last selected option.
The content of $requestData looks like this
$requestData = [
'name' => 'name',
'lastname' => 'lastname',
...
'something' => 'A' // Here I am expeting to have something like 'A,Z'
];
How do I get the desired values?
The controller code belongs to the controller .../components/com_users/ controllers/registration.php in the register method

If you want to get multiple values from select box make that field as array.
Your field name will be - jform[something][]
<select name="jform[something][]" id="something" multiple>
...
</select>

Related

How to get Id field in laravel store function using query builder?

I'm trying to do a create function in laravel crud controller and I need to get the id of categories to store a new subcategory.
In my categories table on mysql db I have the name field and a father id that represent the father category, I'm making a function to create new subcategories but i'm not able to retrieve the father id
My controller:
{
$request->validate([
'name' => 'required|max:100',
//User insert the name of the father category
'category' => 'exists:categories,name'
]);
$category = new Category();
//I try to extract id from table
$father_id = Category::where('name', '=', $request->input('category'))->value('id');
$category->name = $request->input('name');
$category->father_id = $father_id;
$category->save();
// return $father_id;
return redirect()->route('categories.index')->with('success', 'category added successfully');
}
when I try to return 'father_id' variable is empty
I suggest you build your form using either Categories selection with category's id as value.
This will eliminate possibility your user input a random category name.
And at the same time your problem will be solved because you will get category Id directly from user input / submitted data.
Example
<select name="category_id">
<option value="0">No parent category</option>
<option value="1">Category 1</option>
<option value="2">Category 2</option>
....
</select>
And inside your controller
{
$validated = $request->validate([
'name' => 'required|max:100',
'category_id' => 'integer|exists:categories,id'
]);
// optional here you can add extra checker if combination already exists.
// lets create users's new Category
$category = Category::create([
'name' => $validated['name'],
'father_id' => $validated['category_id'],
]);
return redirect()
->route('categories.index')
->with('success', 'New category is added successfully');
}
Note: there might be error using current validation if category_id is 0

Reading a raw array stored in mysql with blade

I have some data i have stored in mysql and it looks like this
["1109255736625955df9fbef.jpg","707361535625955dfa0564.jpg","1126563303625955dfa0c5c.jpg"]
i stored this data as an array in a field called product_images that holds strings.
Is there a way of iterating through this data without making it a php array at first but instead iterate it in blade straight from the database?.
This doesn't work
<div class="row">
#foreach ($product->product_images as $image)
<div class="col-3">
{{$image}}
</div>
#endforeach
</div>
you should use mutators to cast array
Product in model add:
protected $casts = [
'product_images' => 'array',
];
The cast from string to array is done under the hood for you
Your data is stored in database as string, so you should transform it to array. Convenient way to do that is creating Cast in your model. Thanks this you transform data from this column to array on fetch and transforming to json when stored.
protected array $casts = [
'product_images' => 'array'
]

Laravel sortby after select specific option

I would like to add a select field in my application with the option of choosing to sort products by date of addition or price. After selecting a specific option, e.g. sort by price, products returned from the cheapest are returned. I know how to sort products but I do not know how to do it to show sorted products after selecting a specific option, e.g. sort by price. My code :
web.php
Route::get('/{category}', 'ProductController#index');
ProductController:
public function index()
{
$products= Product::latest()->get();
return view('category')->with('products', $products);
}
In your view you could use a form like this to get wich category the user wants to filter:
<form method="get" action="{{route('product.index')}}">
#csrf
<select name="category">
<option value="price">Price</option>
<option value="date">Date</option>
</select>
<button type="submit">Search</button>
</form>
And in your controller you can filter the collection using the selected option:
public function index(Request $request)
{
$products= Product::all()->sortBy($request->category);
return view('category')->with('products', $products);
}

Laravel collective select list with default selected value

I try to populate Laravel forms select list with some data and default selected value like this
#foreach($pesron->state as $state)
{{ Form::select('state[]', \App\City::pluck('Description', 'id'), $state->city->Description,['class' => 'form-control'])!!}
#endforeach
I want $state->city->Description value will be selected by default in select list. Is it possible? I use 5.7.15 version
Looks like you're using Laravel Collective's form helpers.
Take a look here https://laravelcollective.com/docs/5.4/html#drop-down-lists
echo Form::select('size', ['L' => 'Large', 'S' => 'Small'], 'S');

How should I approach making this form in Laravel 5.2?

When I started this project I avoided using Laravel's form helper because it seemed like a convoluted way to make a form that didn't increase readability at all. I now wish that I had because model form binding is a lot harder than I anticipated.
This project is a blog website and posts have been set up to have a many-to-many relationship with tags (models posted at the bottom along with table schemas). When I go to edit a post, I want to have the tags associated with that post already selected in the field, with the option to remove them as well as add new tags. This is what I have to start:
<div class="form-group">
<select class="form-control select2-multi" name="tags[]" multiple="multiple">
#foreach($post->tags as $tag)
<option value="{{ $tag->id }}" selected>{{ $tag->name }}</option>
#endforeach
#foreach($tags as $tag)
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
#endforeach
</select>
</div>
I realized I have a problem in that tags that are printed out as selected also get printed out in the second foreach.
At this point I am stumped. I have two ideas for what to do but I want to follow what would be the best practice so any advice is appreciated:
Use procedural programming in the controller to remove any tags from the tag array that match the $post->tags tags before passing it to the view.
Create a method in the tags controller that builds a query to select all tags except those associated with a post who's ID is passed as a parameter.
My idea for a SQL query that would do this (but I am unsure how to do this in eloquent):
SELECT *
FROM tags
WHERE id NOT IN( SELECT tag_id
FROM posts INNER JOIN post_tag ON posts.id=post_tag.post_id)
Am I making this problem more complicated than it is? Should I just use the form helper to bind the data to my form?
--- Post and Tag Models plus DB Schemas ---
Post model
class Post extends Model
{
protected $table = 'posts';
/**
* Define relationship between posts and categories.
*
* #return eloquent relationship
*/
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
/**
* Define relationship between posts and tags.
*
* #return eloquent relationship
*/
public function tags()
{
return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
}
}
Tag model
class Tag extends Model
{
protected $table = "tags";
public $timestamps = false;
public function posts()
{
return $this->belongsToMany('App\Post', 'post_tag', 'tag_id', 'post_id');
}
}
Schemas
posts(id, title, body, slug, category_id, created_at, updated_at)
tags(id, name)
post_tag(id, post_id, tag_id)
This will be my suggestion.
In you controller
public function edit(Post $post){
$tags = Tag::all();
$postTags = $post->tags->pluck('id')->toArray();
return view('edit', compact('tags', 'postTags'));
}
In your blade
...
#foreach($tags as $tag)
{{--We list all the tags--}}
{{--While listing them, we check if the current tag is part of the tags belonging to this post--}}
{{--If it belongs then we select it--}}
<option value="{{ $tag->id }}" {{ in_array($tag->id, $postTags) ? "selected" : null }}>{{ $tag->name }}</option>
#endforeach
...

Resources