I am making a form using UiComponent. In options.js, I would like to make an ajax call. However It’s getting 404 not found error. I would like to know how we can get the right url.
In the form:
<field name="attribute_id">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">VendorModuleModelSourceMyvalues</item>
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">text</item>
<item name="label" translate="true" xsi:type="string">Attribute</item>
<item name="component" xsi:type="string">Vendor_Module/js/form/element/options</item>
<item name="formElement" xsi:type="string">select</item>
<item name="sortOrder" xsi:type="number">210</item>
</item>
</argument>
</field>
In options.js
define([
'jquery',
'underscore',
'uiRegistry',
'Magento_Ui/js/form/element/select',
'Magento_Ui/js/modal/modal',
'mage/url'
], function ($, _, uiRegistry, select, modal, url) {
'use strict';
return select.extend({
/**
* On value change handler.
*
* @param {String} value
*/
onUpdate: function (value) {
console.log('Selected Value: ' + value);
var field1 = uiRegistry.get('index = field1');
var field2 = uiRegistry.get('index = field2');
field2.hide();
var field3Depend1 = uiRegistry.get('index = field3Depend1');
console.log(field2.visibleValue);
var linkUrl = url.build('customajax');
console.log('linkurl='+linkUrl);
//var name = document.getElementsByName("product[name]")[0].value;
// var type = document.getElementsByName("product[product_category_type]")[0].value;
$.ajax({
url: 'BASEURL????'+linkUrl,
showLoader: true,
data: {form_key: window.FORM_KEY, 'value':value},
type: "POST",
dataType : 'json',
success: function(result){
alert(result);
}
});
return this._super();
},
});
});
It gives 404 not found error. I would like to make an ajax call.
2
Answers
I have tried various method to bring a
url
dynamically into a UI component, but the standard and safe way I think is to add viameta
data of theUI
xml component itself.To inject the dynamic data (not needed if you just want to added a static URL) in the component use the following code:
Form DataProvider.php:
Here, function
getMeta()
is injecting the URL value.UI Component xml field:
Here, I have added
<item name="url" xsi:type="url" path="mymodule/mycontroller/myaction">
the<param name="_nosid">1</param>
</item>
url
key will have the dynamic URL and will be available on JS UI component.Now in
options.js
, use theurl
field as below:Edit: I have updated the answer with the below answer.
It can also be added via
url
xml datatype (Only static urls can be added. No need to modify meta in this case.).UI Component xml field:
Here, I have added
get_custom_url
of typeurl
which will have the URL and will be available on JS.Now in
options.js
, use theurl
field as below: