I have searched but no good solution for now.
I try using is like:
#Html.Editor("userName", new { htmlAttributes = new { value = "ABC" } })
Though, the value doesn't want to appear in renderred HTML.
I need to use Editor element as well as this is kind of 'search' field.
Do you know how is it possible to pass value to Html.Editor?
You should not attempt to override the value attribute in the HtmlHelpers. Instead set the default value in the GET method before you pass the model to the view.
You have indicated userName is not a property of your model (in which case you should be using a view model), but you can use
ViewBag.userName = "yourDefaultValue";
Related
I have a reactive form instantiated using FormBuilder. I would like to use this form for updating or adding a new employee. I am trying to add an expression to the formBuilder constructor that checks to see whether there is a currently selected employee and if there is use one of that employee's interface fields as the value on the form and if there's no current selected employee have a empty string as the value of the specific FormControl.
what i've tried:
'EMP_NM': [this.selectedEmp ? this.selectedEmp.EMP_NM : '', Validators.required],
and then in my editEmployee function:
editCashier(employee: IEmployee) {
this.selectedEmp = employee;
this.empForm.reset();
console.log(this.selectedEmp.EMP_NM);
}
When I do this the value shown on the EMP_NM input field in the HTML doesn't get updated. i've tried setting a setTimeout() in my editEmployee function but that didn't work either. Any idea what might be going wrong here?
I initialize the empForm in my conponent's constructor using formBuilder's group function. Would it help if I moved that to a different function and then call that function everytime the editEmployee function is called to re-initialize the form?
You can update it with patchValue or setValue:
this.empForm['controls']['employee'].patchValue(employee);
Have no clue if it's a nested control but you can go more layers down.
I have a model instance for which I set the attributes from a post request using $my_instance->fill($request_json) and after saving using $my_instance->save() the instance as a record in the database, I want to receive the saved object back with all its attributes using return response()->json($my_instance). Now this works fine as long as I provide all the attributes I set in the protected $fillable = [] on the model class inside the post request body. But when I want to send only part of the attributes in the post request, what happens is that inside tinker I see the skipped attributes are set to null. This is fine. But the problem is when I return using return response()->json($my_instance) I don't see the skipped attributes and I want them to be returned even with them being null in my databse. Is there a way to instruct laravel to do so?
A possible implementation to your question COULD be to:
Allow all possible fields that are getting nulled out to be fillable in your model.
Then, use a middleware with collections to do:
$form_stuff = $request->all();
$form_stuff = collect($form_stuff);
$things_you_want = $form_stuff->only('wanted_field_1','wanted_field_2');
$things_that_should_be_null = $form_stuff->only('nulled_field_1','nulled_field_2');
$keys = array_keys($thins_that_should_be_null);
$values = array_fill(0, count($keys), null);
$new_array_of_nulled_things = array_combine($keys, $values);
var_dump($things_you_want);
var_dump($new_array_of_nulled_things);
die();
WARNING: Since there was no code posted, this is just concept mostly and has not been tested so you will have to play with it to get it work the way you want.
I have a <select> element on a Razor view. It renders as a drop box with language values. I set language via custom cookies and a custom cookie aware view engine.
Let's say I have a cookie set (called language). I want to have a view render with a corresponding <option> marked as selected based on a cookie value. How can I control it with Razor?
Well I would put the select in a strongly typed partial view:
#inherits System.Web.Mvc.WebViewPage<Language>
#Html.DropDownListFor(x => x,
new SelectList((List<Language>)ViewBag.AllLanguages,
"Id",
"Text",
Model==null?-1:Model.Id), "Choose Language")
I would actually set the value in my controller
public virtual ActionResult _MyAction()
{
// get users language
string selectedLanguage = "English"; // default
if(Request.Cookies["language"] != null)
{
selectedLanguage = Request.Cookies["lang"].ToString();
}
// language list
ViewBag.AllLanguages = context.Languages.ToList();
// retrieve language from database - example using EF
ViewBag.SelectedLanguage = context.Languages
.FirstOrDefault(l=>l.Text==selectedLanguage);
and then in my main view
#Html.Partial("LanguageSelect", ViewBag.SelectedLanguage);
This keeps the logic of what language to select away from the presentation of the actual select list. And you could put all that logic in a shared method if it's used a lot.
I have a domain class that needs to have a date after the day it is created in one of its fields.
class myClass {
Date startDate
String iAmGonnaChangeThisInSeveralDays
static constraints = {
iAmGonnaChangeThisInSeveralDays(nullable:true)
startDate(validator:{
def now = new Date()
def roundedDay = DateUtils.round(now, Calendar.DATE)
def checkAgainst
if(roundedDay>now){
Calendar cal = Calendar.getInstance();
cal.setTime(roundedDay);
cal.add(Calendar.DAY_OF_YEAR, -1); // <--
checkAgainst = cal.getTime();
}
else checkAgainst = roundedDay
return (it >= checkAgainst)
})
}
}
So several days later when I change only the string and call save the save fails because the validator is rechecking the date and it is now in the past. Can I set the validator to fire only on create, or is there some way I can change it to detect if we are creating or editing/updating?
#Rob H
I am not entirely sure how to use your answer. I have the following code causing this error:
myInstance.iAmGonnaChangeThisInSeveralDays = "nachos"
myInstance.save()
if(myInstance.hasErrors()){
println "This keeps happening because of the stupid date problem"
}
You can check if the id is set as an indicator of whether it's a new non-persistent instance or an existing persistent instance:
startDate(validator:{ date, obj ->
if (obj.id) {
// don't check existing instances
return
}
def now = new Date()
...
}
One option might be to specify which properties you want to be validated. From the documentation:
The validate method accepts an
optional List argument which may
contain the names of the properties
that should be validated. When a List
is passed to the validate method, only
the properties defined in the List
will be validated.
Example:
// when saving for the first time:
myInstance.startDate = new Date()
if(myInstance.validate() && myInstance.save()) { ... }
// when updating later
myInstance.iAmGonnaChangeThisInSeveralDays = 'New Value'
myInstance.validate(['iAmGonnaChangeThisInSeveralDays'])
if(myInstance.hasErrors() || !myInstance.save(validate: false)) {
// handle errors
} else {
// handle success
}
This feels a bit hacky, since you're bypassing some built-in Grails goodness. You'll want to be cautious that you aren't bypassing any necessary validation on the domain that would normally happen if you were to just call save(). I'd be interested in seeing others' solutions if there are more elegant ones.
Note: I really don't recommend using save(validate: false) if you can avoid it. It's bound to cause some unforeseen negative consequence down the road unless you're very careful about how you use it. If you can find an alternative, by all means use it instead.
for String and Object type, I can set the default parameter to null to indicate that it was not set by the caller. Is there a mechanism in flex3 to do the same for the Number type?
So for instance:
public function myMethod( stringVar:String=null, ObjectVar:Object=null, numberVar:Number )
{
...
}
I could do the following, but it just feels ugly
public function myMethod( numberVarObj:Object=null )
{
var numberVarSet:Boolean=true;
if( numberVarObj == null ) {
numberVarSet = false;
}
and then everywhere I want to use numberVar I can check for numberVarSet and cast as a Number.
I suppose you could always try:
var numberVar:* = null;
And then set it to a number when you want . . . It would be nice to have a solution that is strongly typed though.
Another option, as specified in Adobe's Docs (scroll down to default values), would be to treat the value NaN as null. However, if your data has ANY chance of containing a NaN value, this is a horrible idea.
I'd recommend the "ugly" solution you have, but if you really want another option you can use NaN and then use isNaN(num) to check the value.