Change select field options in client script in NetSuite - javascript

I have a client script runs on Suitelet.
On Suitelet we have a sublist which has many select columns.
Let's say we have Select 1 and Select 2.
Select 2 options should be different if you change the option in Select 1.
Could this be done in Client Script? or in that Suitelet?
Any help would be appreciated.
`
var select1= sublist.addField({
id: 'custpage_select1',
label: 'Select1',
type: ui.FieldType.SELECT
});
var select2= sublist.addField({
id: 'custpage_select2',
label: 'Select2',
type: ui.FieldType.SELECT
});
`
In client script when the field is changed, I want to change options of Select 2 depend on Select 1.
function fieldChanged(scriptContext){
if(scriptContext.fieldId=="custpage_select1"){
let page = currentRecord.get();
var select2 = page.getField({fieldID:"custpage_select2"});
select2.removeSelectOption({value:"value1"});
}
}
But this shows me an error that
Cannot read properties of null
Thank you

Yes. You can use the N/currentRecord module in your client script with getField() and removeSelectOption().
let page = currentRecord.get();
const select2 = page.getField({
fieldId: 'custpage_select2'
});
select2.removeSelectOption({
value: 'option1'
});

Related

Set the field values to the values from the selected record in tree Extjs

In my application, the two components Ext.tree.Panel and Ext.form.Panel
When I click on the tree entry I need to set the field values ​​to the values ​​from the selected record.
When I click on the entry, the event handler function in the controller is triggered:
...
showDataFields: function(view, record, item, index, event) {
//got a form with fields
var panel = view.up('mainpanel');
var formfield = panel.down('mainform');
//got the selected entry in the tree
sel = view.getSelectionModel().getSelection()[0];
console.log(sel)
//How to assign values from selected record to form fields?
}
...
How can i do this?
Example in fiddle
The showDataFields method in the controller file on line 37
You can use loadRecord, which will map your record data to your form by name property. First retrieve form and then set your record to it:
showDataFields: function(view, record, item, index, event) {
...
var form = panel.down('storagepaneltype');
form.loadRecord(record);
}
Also, you need to change "name" property from name to text to make form match record property. In Fiddle.view.StoragePanel:
items: [{
xtype: 'textfield',
name: 'text', //<-- here
fieldLabel: 'Наименование',
itemId: 'name_field',
value: '',
//bind: '{person.name}'
}
Here's the FIDDLE

Why does my Django form show choice not available error?

I am trying to build a dynamic form in Django template.
I have two dropdown selections. When the user selects an option in the first one, the available choices in the second dropdown changes dynamically. Here is the jQuery code I use to change the choices in the second dropdown element.
$(document).on("change", "[id^=id_form][id$=brand]", function() {
var $value = $(this).val();
var $id_prefix = $(this).attr('id').slice(0, -5);
$auto_type = $("#" + $id_prefix + "auto_type");
$.ajax({
type: 'GET',
url: '/europarts/filter/auto/type/with/brand/' + String($value),
success: function(data) {
$auto_type.html(data);
}
});
});
You can see that it fetches some HTML from a link which is basically a bunch of options which will replace the current ones. Here is the code:
{% for auto_type in auto_types %}
<option value="{{ auto_type.id }}">{{ auto_type.name }}</option>
{% endfor %}
Here are my forms:
class ListForm(forms.ModelForm):
class Meta:
model = List
fields = ['ref_no']
class ProductCreateForm(forms.Form):
brand = forms.ModelChoiceField(queryset=Brand.objects.all(), initial=Brand.objects.first())
auto_type = forms.ModelChoiceField(queryset=AutoType.objects.filter(brand=Brand.objects.first()), empty_label=None)
part_no = forms.CharField(max_length=50)
description = forms.CharField(max_length=255)
quantity = forms.IntegerField()
unit = forms.CharField(max_length=20, initial='piece(s)')
cost_price = forms.IntegerField(required=False)
selling_price = forms.IntegerField(required=False)
I am using a dynamic formset jquery library to save multiple Products with a List.
This works fine till now!
However after I change the options like this and try to submit the form, the form page gets loaded again with the default options in the second dropdown and not the changed ones along with an error that says:
Select a valid choice. That choice is not one of the available choices.
Here is the request.POST value when the form is submitted.
<QueryDict: {'form-MAX_NUM_FORMS': ['1000'], 'form-1-description': ['lskdjf'], 'form-1-auto_type': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-0-quantity': ['1'], 'form-0-brand': ['2'], 'form-0-part_no': ['293847'], 'form-0-auto_type': ['2'], 'form-0-unit': ['piece(s)'], 'form-0-description': ['slkdfj'], 'form-1-part_no': ['928374'], 'form-TOTAL_FORMS': ['2'], 'form-1-quantity': ['1'], 'form-INITIAL_FORMS': ['0'], 'ref_no': ['REF230498203948'], 'csrfmiddlewaretoken': ['WYN08Hi2YhwTSKPS8EnLaz94aOz33RVfFMjwYeHr3rMxBImxn7ggSLYHwguIbuL0'], 'form-1-brand': ['2'], 'form-1-unit': ['pieces']}>
You can see 'form-1-auto_type': ['3'] which was 'form-1-auto_type': ['1'] originally. The form is submitted when the original value is there, but after the dynamic change in value it shows the above error.
This error is shown for the second dropdown. How can I fix this?
When the form is being validated it checks whether the option exists in the choices for the field, in this case:
queryset=AutoType.objects.filter(brand=Brand.objects.first())
It works only when you select an option from the first brand.
To make it work you need to update the choices for the auto_type field before it validates the data or it might be easier not to limit the choices of auto_type to any brand and then update the select element in JavaScript when the page loads to show only the options of the first brand.

Using angularjs-dropdown-multiselect for dropdownwith checkbox, how to disable particular options using their id's

Here is the code where I have used the plugin to display options with checkbox in angular.I need to disable particular/set of options based on a condition. the ng-disable does not seem to help. Jquery needs to identify each li or option using id's.
<div ng-if="tab===1"
class="col-md-3 padd0LeftRight marTop5 width150"
ng-dropdown-multiselect=""
options="severities"
selected-model="$parent.severityModel" checkboxes="true"
extra-settings="severitySettings"
translation-texts="SeverityText"></div>
Controller:
$scope.severityModel =[];
$scope.severitySettings = {
showCheckAll: false,
showUncheckAll:false,
externalIdProp: ''
};
$scope.SeverityText = {
buttonDefaultText:"Severity "
};
{label: $scope.resource['casepage.filter.ciscopending.internal'],
name:'Cisco_Pending'
}];
$scope.severities = [
{label:$scope.resource['landingpage.label.severity1'], name:'1',id:'1'},
{label:$scope.resource['landingpage.label.severity2'], name: '2',id:'2'},
{label:$scope.resource['landingpage.label.severity3'], name: '3',id:'3'},
{label:$scope.resource['landingpage.label.severity4'], name: '4',id:'4'}
];
Onclick of a button or a checkbox, I have to disable some options in the dropdown. How do we do that? Can anyone suggest here. Thanks.

changing data of select2 with x-editable without re-setting source option

How to keep the source of option values updated in x-editable
without re-initialising the editable element with source.
Here is the sandbox : http://jsfiddle.net/wQysh/322/
HTML
<p>X-editable (dev)</p>
<div>
<button id="controller">Add</button>
</div>
<div>
<button id="controller1">Remove</button>
</div>
<div>
<button id="controller2">Update</button>
</div>
<div style="margin: 50px">
</div>
<div style="margin: 50px">
</div>
<div style="margin: 50px">
</div>
<div style="margin: 50px">
</div>
JS :
$.fn.editable.defaults.mode = 'inline';
var count = 4, sources = [];
for(var i = 1; i <= count; i++){
sources.push({ id : i, text : String(i) })
}
var getSource = function() {
//i want this function must be called whenever available options is rendred. to ensure i used JSON.parse
return JSON.parse(JSON.stringify(sources));
};
$('#controller2').click(function(e){
count++;
sources[2].text = String(count);
//to verify live changes, if a new record updated in sources and used instantly
$('#username').editable('setValue', [1, count]); $('#username2').editable('setValue', count);
});
$('#controller').click(function(e){
count++;
sources.push( {id : count, text :String(count) });
//to verify live changes, what if a new record added in sources and used instantly
$('#username').editable('setValue', [1, count]); $('#username2').editable('setValue', count);
});
$('#controller1').click(function(e){
count++;
var a = sources.pop();
//to verify live changes by selecting value that is not present in the list. It should escape those, print the rest all if available in list
$('#username').editable('setValue', [1, a.id]); $('#username2').editable('setValue', a.id);
});
$('#username').editable({ //to keep track of selected values in multi select
type: 'select2',
url: '/post',
autotext : 'always',
value : [1,2],
source : getSource,
emptytext: 'None',
select2: {
multiple : true
}
});
$('#username2').editable({ //to keep track of selected values in single select
type: 'select2',
url: '/post',
autotext : 'always',
value : 2,
source : getSource,
emptytext: 'None',
select2: {
multiple : false
}
});
$('#username3').editable({ //to keep track of available values in multi select
type: 'select2',
url: '/post',
autotext : 'always',
value : null,
source : getSource,
emptytext: 'None',
select2: {
multiple : true
}
});
$('#username4').editable({ //to keep track of available values in single select
type: 'select2',
url: '/post',
autotext : 'always',
value : null,
source : getSource,
emptytext: 'None',
select2: {
multiple : false
}
});
//ajax emulation. Type "err" to see error message
$.mockjax({
url: '/post',
responseTime: 400,
response: function(settings) {
if(settings.data.value == 'err') {
this.status = 500;
this.responseText = 'Validation error!';
} else {
this.responseText = '';
}
}
});
Requirement :
Whenever i add new item in sources, if item is not selected then it should be updated in available options otherwise if selected then view should have updated value at element.
Whenever i update an item in sources, if item is not selected then it should be updated in available options otherwise if selected then view should have updated value at element.
Whenever i delete an item in sources, if item is not selected then it should be removed from the available options otherwise if selected then view should have "None" value (if single select) and rest element values (if multi select) at element.
Not allowed:
to reinit the widget
to reinit the source option
I hope this is possible. But struggling to get the result.
EDIT2 : code did not worked when i used JSON.parse over stringified 'sources' Problem is still unresolved. New fiddle : http://jsfiddle.net/wQysh/322/
(EDIT1 was misleading this question so removed EDIT1)
EDIT3 : so far i am able to achieve this http://jsfiddle.net/wQysh/324/
Here problem is that previous selected values are not rendered, so can't remove the items if selected previously in multi-select
EDIT4: not completely solved, http://jsfiddle.net/wQysh/339/. After add or update the available option does change but after setting that new record, does not reflect in html element after submit.
the answer is to use a custom display function
here is the updated fiddle. http://jsfiddle.net/wQysh/357/
Every time we 'setValue' to editable or on close event editable's 'display' function is called.
in display function existing values is checked by this function
$.fn.editableutils.itemsByValue
where the third parameter accepts the idKey. If we do not provide third parameter while calling this function, it by default takes 'value' as idKey. and 'value' as idKey should not be used when we are using to load array data. ref : http://ivaynberg.github.io/select2/#data_array.
I added display function in which third parameter is 'id'.
and i got the desired result

jquery autocomplete in variable length list

Trying to figure out how to do this, using Sanderson begincollectionitems method, and would like to use autocomplete with a field in each row.
I think I see how to add a row with an autocomplete, just not sure the approach for existing rows rendered with guid.
Each row has an of field that the user can optionally point to a record in another table. Each autocomplete would need to work on the html element idfield_guid.
I'm imagining using jquery to enumerate the elements and add the autocomplete to each one with the target being the unique of field for that row. Another thought is a regex that maybe let you enumerate the fields and add autocomplete for each in a loop where the unique field id is handled automatically.
Does that sound reasonable or can you suggest the right way? Also is there a reasonable limit to how many autocomplete on a page? Thanks for any suggestions!
Edit, here's what I have after the help. data-jsonurl is apparently not being picked up by jquery as it is doing the html request to the url of the main page.
$(document).ready(function () {
var options = {
source: function(request, response) {
$.getJSON($(this).data("jsonurl"), request, function (return_data) {
response(return_data.itemList);
});
},
minLength: 2
};
$('.ac').autocomplete(options);
});
<%= Html.TextBoxFor(
x => x.AssetId,
new {
#class = "ac",
data_jsonurl = Url.Action("AssetSerialSearch", "WoTran", new { q = Model.AssetId })
})
%>
And the emitted html look okay to me:
<input class="ac" data-jsonurl="/WoTran/AssetSerialSearch?q=2657" id="WoTransViewModel_f32dedbb-c75d-4029-a49b-253845df8541__AssetId" name="WoTransViewModel[f32dedbb-c75d-4029-a49b-253845df8541].AssetId" type="text" value="2657" />
The controller is not a factor yet, in firebug I get a request like this:
http://localhost:58182/WoReceipt/Details/undefined?term=266&_=1312892089948
What seems to be happening is that the $(this) is not returning the html element but instead the jquery autocomplete widget object. If I drill into the properties in firebug under the 'element' I eventually do see the data-jsonurl but it is not a property of $(this). Here is console.log($this):
You could use the jQuery UI Autocomplete plugin. Simply apply some know class to all fields that require an autocomplete functionality as well as an additional HTML5 data-url attribute to indicate the foreign key:
<%= Html.TextBoxFor(
x => x.Name,
new {
#class = "ac",
data_url = Url.Action("autocomplete", new { fk = Model.FK })
})
%>
and then attach the plugin:
var options = {
source: function(request, response) {
$.getJSON($(this).data('url'), request, function(return_data) {
response(return_data.suggestions);
});
},
minLength: 2
});
$('.ac').autocomplete(options);
and finally we could have a controller action taking two arguments (term and fk) which will return a JSON array of suggestions for the given term and foreign key.
public ActionResult AutoComplete(string term, string fk)
{
// TODO: based on the search term and the foreign key generate an array of suggestions
var suggestions = new[]
{
new { label = "suggestion 1", value = "suggestion 1" },
new { label = "suggestion 2", value = "suggestion 2" },
new { label = "suggestion 3", value = "suggestion 3" },
};
return Json(suggestions, JsonRequestBehavior.AllowGet);
}
You should also attach the autocomplete plugin for newly added rows.

Categories

Resources