Laravel search form using database - forms

I have a search form with three fields: Department, Role and Location which I'm calling Contacts search and it is to be on multiple pages.
Here is a picture:
To this extent, I made it a Blade include so I could just re-use it wherever I need it.
All of the values for these fields are available to me in the Users table as I could do the following:
SELECT DISTINCT department, role, location FROM users
This would give me all of the unique roles, departments and locations.
However, for me to populate this form via the database would I have to pass the data to the parent view every time?
For instance, I was thinking something like this.
In Controller
$formFields = User::distinct()->get(['department', 'role', 'location']);
In view
#foreach(formFields as $field)
$field->department
...
...
#endforeach
The only issue is, surely I would have to send this data to every view that uses the form?
Alternatively, do I just make a SearchController that uses the User model to feed into it?
Is it possible to feed data to a partial view in this way?
Update
View composers do seem to be the way to go, however I don't feel this is valid:
view()->composer('layouts.quick-search', function($view) {
$view->with('departments', \App\User::distinct()->get(['department']),
'locations', \App\User::distinct()->get(['location']),
'roles', \App\User::distinct()->get(['role']));
});
As it doesn't seem to like multiple variables.
I also tried the following:
<select class="form-control transparant" id="department" name="department">
#foreach($departments as $department)
<option value="{{ $department }}">{{ $department }}</option>
#endforeach
</select>
But this filled the select box with:
{"department":"Digital","profile":null}
This is clearly an array, but does this mean I'll have to JSON decode this?

As I mentioned in my comment, you could do something like this:
In view
#php $formFields = \App\User::distinct()->get(['department', 'role', 'location']); #endphp
#foreach(formFields as $field)
$field->department
...
...
#endforeach
Another way to do this would be creating a group of all those views that use the partial view. Apply a middleware to that group where you assign the data to the request or share the data to the views using View::share()

View composers are perfect for this.
You create a separate view for the form, something like search and put this in a service provider:
use Illuminate\Support\Facades\View;
use App\User;
// ...
publlic function boot()
{
View::composer('search', function ($view) {
$view->with([
'formFields' => User::distinct()->get(['department', 'role', 'location']);
]);
});
}
Now every time the search view will be used, this query will be executed and the results will be passed to the view.

Related

bind menu and submenu from database in asp net core entity framework mvc

I have 2 tables in database Industry and Category. They are joined using IndustryId as primary key and Foreign key in tables.Now I want to show Industry as my main menu item and Related categories as my sub menu items of respective industries. I am using asp net mvc enity framework as my coding architecture with visual studio 2017.This is my first application on this architecture I want a brief explanation including models views and controllers step by step.I have done this binding earlier on asp net web forms without mvc. But entity frameworks is seems to be totally different from previous versions.
Edit based on user comment, he want to bind the data on load, making nested list, I will leave my old answer as it might help someone else, I will add the new answer as well,
my suggestion is you pass List of Industries as a ViewBag, since there is foriegn key in categories which is industryid relating to industry table, ef will detect that relationship and represent it in your Industry Model as virtual Collection<Category> Categories, this represents all categories associated with this industry.
what you can do is pass it then using razor syntax do something like this in your view
in your controller you pass it as viewbag
ViewBag.Industries = dbContext.Industries.Include(x => x.Categories).ToList();
then in your view
<!-- init your list -->
<ul>
<!-- loop through your viewbag -->
foreach (var x in (List<Industry>) ViewBag.Industries)
{
<li> x.IndustryName
<!-- init your sub menu -->
<ul>
<!-- loop through your categories of this industry x -->
foreach(var c in x.Categories)
{
<li> c.CategoryName </li>
}
</ul>
</li>
}
<!-- loop end, close your list -->
</ul>
For People looking to update their menu content dynamically according to another menu value, read below:
What I do to solve such thing is, first create action which accepts industry id and return List or categories, I use ajax to call this action whenever my industry id list change in the front end (change event listener), then get the return as list of object, bind the data to my sub menu using jquery.
something like
public ActionResult GetCategories(int IndustryID)
{
// this simple select query, retrieves all categories that have industry id provided
var categories = dbContext.Categories.Where(c => c.IndustryId == IndustryID).ToList();
return Json(categories);
}
ajax code
// industryId is the id of industry in your view, apply change event listener
$('#industryId').change(function () {
// ajax call, get data
$.ajax({
type: "POST",
url: '#Url.Action("GetCategories", "controllerhere")',
data: { IndustryID: this.value},
dataType: "json"
}).done(function(data){
// Data recieved, get categories list, empty it, bind the new data
var ddl = $("#categoriesList");
ddl.empty();
ddl.append($('<option>', {value: 0,text: 'Select'})); //Newly added
// categoryID and CategoryName are properties in your category, these Names I assumed, they might change depending on your Model
$.each(data, function () {
ddl.append($('<option></option>').attr("value", this.CategoryID).text(this.CategoryName));
});
});
});
I hope this answered your question, I am not sure what did you mean when you said entity framework is different, you can ask me more specific questions maybe i can help

Laravel 4 - get data from multiselect form

I'm using Laravel 4, and I have two tables related 'Many to many': 'Actividad' and 'Material'. Every Actividad can have one or more Materials, and every Material can belong to one or more Actividad.
So, I have made a form to create a new Actividad where you can save one or more Materials. I've done that with a multiselect input. Like that:
{{ Form::label('material_id', 'Material necesario:') }}
<p>{{ Form::select('material_id', $material_id, Input::old('material_id'), array('multiple')) }}</p>
I don't know if I'm doing correctly but, before saving anything, my first problem is that I'm only obtaining one result. I suppose I should get every option 'checked' in the form... The relevant part of my Controller is:
$material = Input::get('material_id');
return var_dump($material);
I should obtain a list of options selected, but the result of that in my browser is:
string(1) "1"
This is the first time I'm working with tables related in this way, and probably I'm doing something wrong (in the form, in my controller, in my Models,...)
Thank you very much for your help!!
Just change your code to this
{{ Form::select('material_id[]', $material_id, Input::old('material_id'), array('multiple')) }}
I hope this helps.
if you are using custom response handlers on the client side such in the case of submitting info with AJAX, all you need to do is to simple add "[]" to the name of the select control.
e.g.
<select name="material_id[]" multiple>
This is the same case as with regular PHP. The other methods are required if you want Laravel to handle the form elements for you when rendering a new response/view. ( page reload ). This reload doesn't happen with REST requests.

Defining sort-order of associated model select box from CakePHP's FormHelper?

In this instance I'm working with two models: Departments, and Users.
Departments belongsTo Users
(In this instance, a user is a department manager [null allowed].)
Using FormHelper, I simply defined the selection of the User id as:
echo $this->Form->input('user_id', array('label'=>'Department/Group Manager (leave blank if none)', 'empty' => true));
By default, FormHelper seems to order the selection items by User.id ASC (the HTML select element's "value" property). To make things nicer in the add.ctp form, I created a virtual field as "Lastname, Firstname" to be used as the User model's display field:
public $virtualFields = array(
'name' => "CONCAT(User.lastName, ', ', User.firstName)"
);
public $displayField = 'name';
This worked great. Unfortunately, I'd love to be able to order the items in the rendered select box by the virtual field's value, ascending (or User.lastName in this case) instead of by User.id. I was unable to figure out a way to do this using FormHelper. Is there another way to do this (if FormHelper can't do it)?
MVC:
The MODEL retrieves the data (business logic).
The CONTROLLER sets the data for the view [$this->set()].
The VIEW simply handles your output, and any logic that is not capable of being handled elsewhere.
Using Cake convention based on how the cake bake output is created, you'd want to set the ORDER BY clause in the call to the model's find() method in your controller, related to the particular view. In this case, your Department's add() method.
public function add(){
// ... other code ...
$users = $this->Department->User->find('list', array('order' => array('lastName' => 'asc'));
$this->set(compact('users'));
}
Be aware that if you are using the Containable Behavior you may need to adjust its settings to achieve the default (most likely working) code example above.

How to reuse codeigniter form on multiple pages

I have a simple search form I want to reuse across multiple pages in my codeigniter application. For example, right now I have a search form in the sidebar and I'm planning on displaying that sidebar on the index, about, and other pages.
I want to have the form validation display errors on the same page the users submits the form from.
For example:
User is on About page.
User submits form with invalid data
User sees error in the sidebar on the About page
and
User is on Index page.
User submits form with invalid data
User sees error in the sidebar on the Index page
But I'd like to reuse that form validation logic. I just want it to display the error on whichever page the user posted from.
Any ideas how to do that? Sorry for the noob question, I'm pretty new to CI.
Here you have to think globally.
Step.1 : Make one view file : display.php
which contains :
<div id = "main">
<div id = "header">
[load header file here]
</div>
<?php
if(validation_errors() != '') {
?>
<div id = "error">
<?=validation_errors()?>
</div>
<?php
}
?>
<div id = "content">
<?=$page?>
</div>
<div id = "footer">
[load footer file here]
</div>
</div>
Step.2 : About us Page.(controlller)
.... Your data ....
at end of controller function
$data['page'] = 'aboutus';
$this->load->view('display',$data);
With regards to your comment on the above question you could use Flash data
With the assumption that you have the session library loaded, here is a helper function.
function last_page($page = null){
$ci = get_instance();
if($page === null)
return $ci->session->flashdata('last_page');
$ci->session->set_flashdata('last_page', $page);
}
then you can call last_page('about'); at the top of the about page, and then when you want to find out what the last page you were on was you can just call last_page(); with no params.
In the User Guide, there's different ways to configure sets/groups of rules. Then you can simply have something like:
if ($this->form_validation->run('signup') == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
Which will run your "signup" group of validations. To me, this is the cleanest way to achieve reusable validation rules.
This is a perfectly valid question.
I'm not a PHP expert, nor a CI expert, but the fact is sometimes you want to post to a controller that didn't create the view from which you're posting. Which means posting back to itself is not going to work.
I came across this post on the Ellislab forum:
http://ellislab.com/forums/viewthread/217176/
On this page, There are 2 methods of going about it. Both of which use flashdata and both of which are totally valid, IMHO.
The first: create a helper function
http://ellislab.com/forums/viewreply/1003010/
The second: extend the CI_Form_Validation Class.
http://ellislab.com/forums/viewreply/1047536/
The second is the way I went as it seems cleanest although some may argue whether the form validation class should know anything about flash data.

How do i preserve form input - after submiting form with dynamic menu list ?? Zend framework

Im trying to preserve the user inputs from dynamic menu dropdown lists - I have an number of drowpdowns and a user input text field , when the user submits the form after selecting the options from the dropdowns.
I would like to be able to preserve the last choices made so the user does not have to reselect the options again when re posting the form with another value in the text field, i would also like this to work on errors as well ?
Im using ZF to validate the form.
i have tried the follwing code in the value attr of the option:
<option value="<?php if ($_POST && errors) {
echo htmlentities($_POST['CategoryID'], ENT_COMPAT, 'UTF-8');
}?>">Main Category</option>
But does not seem to work ?
I have a static options "Main Category" ect. which is what the form defaults to after submiting
can anyone help me on this one ??
Thanks in advance
I would highly recommend using Zend_Form. If that is not possible, I would next use Zend_View Helpers to build your HTML manually. Then you can use the formSelect in your view like this:
echo $this->formSelect('CategoryId', $selected, $attribs, array(
'main' => 'Main Category'
// ... other options
));
Where $selected variable equals to one of the following: posted value(s), default value(s), or is null and $attribs variable is simply attributes for the select element.