How I can get an object in HTML?
I have this:
#Html.DisplayFor(model => model.Product.Keys.Where(x => x.TransactionID == model.TransactionID))
but here I have an object, and I want to display only one value.
I tried something like this:
#{
var key = model.Product.Keys.Where(x => x.TransactionID == model.TransactionID);
}
but model name doesn't exist in the current context.
Any ideas?
You should to use Model
#{
var key = Model.Product.Keys.Where(x => x.TransactionID == Model.TransactionID);
}
Related
I am trying to import data from excel file into database tables in Laravel. I have successfully imported the data but If I mistakenly leave a field empty then I get error that column cannot be null. So I need check if the all necessary data is provided.
I use this code.
IndependentContractor::create(['staff_id' => $staff->id, 'address' => $excel_row['address'], 'longitude' => $excel_row['longitude'], 'latitude' => $excel_row['latitude'], 'tax_id' => $excel_row['tax_id'], 'business_name' => $excel_row['business_name'], 'person_incharge' => $excel_row['person_incharge'], 'phone_of_person_incharge' => $excel_row['phone_of_person_incharge'], 'general_manager' => $excel_row['general_manager'], 'phone_of_general_manager' => $excel_row['phone_of_general_manager']]);
I can use If() to check the data but I will have to repeat this in almost 7 places because there are 7 different tables in which data is being stored.
also if statement will look like this.
if(!empty($excel_row['address']) && !empty($excel_row['longitude']) && !empty($excel_row['latitude']) && !empty($excel_row['business_name']) and so on )
So is there any better way to achieve this?
Thanks.
you can try using looping, using the array_key, assumming database column name = excel column name
example :
$data = [];
foreach($excel_row as $key => $value){
if(!empty($excel_row[$key])){
$data[$key] = $excel_row[$key];
}else{
dd('empty column found'); //your code here
}
}
//if everything goes fine
IndependentContractor::create($data);
class UsersImport implements ToModel, WithUpserts
{
/**
* #return string|array
*/
public function uniqueBy()
{
return 'email';
}
if (!isset($row[0])) {
return null;
}
return new User([
'name' => $row[0],
]);
}
I have a key value pair that I am inserting into a model with the following:
public function addContactDetail(Request $request){
$data = $request->all();
$contact_id = $data['contact_id'];
$contact = Contact::find($contact_id);
$details = $contact->details;
$details[$data['label']] = $data['value'];
$contact->details = $details;
$contact->save();
return response()->json($contact);
}
After insert it sometimes puts it randomly in the middle of the object. How do I keep it at the end?
If you are using Laravel 5 or greater version,
Try casting your json column into array in eloquent using mutators. like this.
inside your Contact Model
protected $casts = [
'details' => 'array',
];
By doing so, I guess you will get what you want. Try it and let me know
Controller side:
$regs = Model::all('id','name');
return view('aview',compact('regs'));
View side:
{{ Form::select('id', $regs) }}
The dropdown gets rendered and populated but displays JSON objects such as {"id:1","name: Aname"} instead of displaying Aname and setting the post value to 1
Try this
In your controller
$regs = Model::pluck('name','id');
Keep your view same
Hope this will work
You can populate like this:
{!! Form::select('id', $regs->lists('name', 'id'), null, ['class' => 'form-control']) !!}
Form::select accepts four parameters:
public function select($name, $list = [], $selected = null, $options = []);
The name of the html field
the list of options
the selected value
an array of html attributes
You can generate the list by using
$regs = Model::all('id','name');
$plucked = $regs->pluck('name', 'id');
// $plcuked = ['id1' => 'name1', 'id2' => 'name2' ...]
And the blade code should look like this
{{ Form::select('name', $plucked, null, ['class' => 'form-control']); }}
I maybe making this problem a bit complicated but I think its worth using the plugin.
You can take the use of very popular plugin - Select2. This plugin of jQuery helps you to fetch data from server and populate the fetched data into our dropdown in minutes. Your code goes like this.
// Code in your Controller Method
$regs = Model::all();
$data = [];
foreach($regs as $reg) {
$data[] = [
'id' => $reg->id,
'text' => $reg->name
];
}
return json_encode(['items' => $data]);
// Code in your desired View
<select id="select_items"></select>
// Code in js
$('#select_items').select2({
ajax: {
url: '/example/api', // <--------- Route to your controller method
processResults: function (data) {
return {
results: data.items
};
}
}
});
You can also integrate search options using this plugins as it helps you to fetch results based on your search keywords (for more see Select2 Examples). Hope this helps you to solve your problem.
i am trying to extract some data between divs.
<div class="movie_general"><div class="img"><a href="/Movies.html" title="Watch Movie">
Fore example if i want the link "/Movies.html" i used:
string hrefValue = doc.DocumentNode
.Descendants("div")
.Where(x => x.Attributes["class"].Value == "movie_general")
.Select(x => x.Element("a").Attributes["href"].Value)
.FirstOrDefault();
MessageBox.Show(hrefValue);
but i get a NullReferenceException at Where(x => x.Attributes["class"].Value == "movie_general")
What am i doing wrong?
It happens because the Linq provider must iterate through all other nodes in the document to check if it matches your search. This document must have at least one div which does not have a class attribute. So, the error happens by trying to read the Value property of an attribute which does not exist.
Replace this
.Where(x => x.Attributes["class"].Value == "movie_general")
.Select(x => x.Element("a").Attributes["href"].Value)
with this
.Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "movie_general")
.Select(x => x.Element("a") != null && x.Element("a").Attributes["href"] != null ? x.Element("a").Attributes["href"].Value : string.Empty)
If you already know the class and that the a tag is subordinate to that, why not just grab it directly using:
HtmlDocument doc = new HtmlDocument();
doc.Load("C:\\temp\\stackhtml.html");
string link = doc.DocumentNode.SelectSingleNode("//div[#class='movie_general']//a").GetAttributeValue("href", "unkown");
Console.WriteLine(link);
Console.ReadLine();
and the result:
I added closing div tags to your example so that I could scrape it and dumped it in a file on my c drive:
<div class="movie_general">
<div class="img">
<a href="/Movies.html" title="Watch Movie">
</div>
</div>
How do I get the collection of errors in a view?
I don't want to use the Html Helper Validation Summary or Validation Message. Instead I want to check for errors and if any display them in specific format. Also on the input controls I want to check for a specific property error and add a class to the input.
P.S. I'm using the Spark View Engine but the idea should be the same.
So I figured I could do something like...
<if condition="${ModelState.Errors.Count > 0}">
DisplayErrorSummary()
</if>
....and also...
<input type="text" value="${Model.Name}"
class="?{ModelState.Errors["Name"] != string.empty} error" />
....
Or something like that.
UPDATE
My final solution looked like this:
<input type="text" value="${ViewData.Model.Name}"
class="text error?{!ViewData.ModelState.IsValid &&
ViewData.ModelState["Name"].Errors.Count() > 0}"
id="Name" name="Name" />
This only adds the error css class if this property has an error.
<% ViewData.ModelState.IsValid %>
or
<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %>
and for a specific property...
<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection
To just get the errors from the ModelState, use this Linq:
var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
Condensed version of #ChrisMcKenzie's answer:
var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
This will give you one string with all the errors with comma separating
string validationErrors = string.Join(",",
ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToArray());
Putting together several answers from above, this is what I ended up using:
var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToList();
validationErrors ends up being a List<string> that contains each error message. From there, it's easy to do what you want with that list.
Thanks Chad! To show all the errors associated with the key, here's what I came up with. For some reason the base Html.ValidationMessage helper only shows the first error associated with the key.
<%= Html.ShowAllErrors(mykey) %>
HtmlHelper:
public static String ShowAllErrors(this HtmlHelper helper, String key) {
StringBuilder sb = new StringBuilder();
if (helper.ViewData.ModelState[key] != null) {
foreach (var e in helper.ViewData.ModelState[key].Errors) {
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "field-validation-error");
div.SetInnerText(e.ErrorMessage);
sb.Append(div.ToString());
}
}
return sb.ToString();
}
Here is the VB.
Dim validationErrors As String = String.Join(",", ModelState.Values.Where(Function(E) E.Errors.Count > 0).SelectMany(Function(E) E.Errors).[Select](Function(E) E.ErrorMessage).ToArray())
If you don't know what property caused the error, you can, using reflection, loop over all properties:
public static String ShowAllErrors<T>(this HtmlHelper helper) {
StringBuilder sb = new StringBuilder();
Type myType = typeof(T);
PropertyInfo[] propInfo = myType.GetProperties();
foreach (PropertyInfo prop in propInfo) {
foreach (var e in helper.ViewData.ModelState[prop.Name].Errors) {
TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "field-validation-error");
div.SetInnerText(e.ErrorMessage);
sb.Append(div.ToString());
}
}
return sb.ToString();
}
Where T is the type of your "ViewModel".
Got this from BrockAllen's answer that worked for me, it displays the keys that have errors:
var errors =
from item in ModelState
where item.Value.Errors.Count > 0
select item.Key;
var keys = errors.ToArray();
Source: https://forums.asp.net/t/1805163.aspx?Get+the+Key+value+of+the+Model+error