I want to set a default value for an uiComponent field (shipping_id in this case) from the DataProvider (not from the form's XML, but from PHP). This is because the default value is dynamic (i am creating a new record based on a shipping id).
In my DataProvider:
 public function getData()
 {
 foreach ($this->collection->getItems() as $item) {
 $this->_loadedData[$item->getId()]['general'] = $item->getData();
 }
 if (empty($this->_loadedData)) {
 //set default values
 /** @var ShipmentInterface $shipment */
 $shipment = $this->persistor->get('shipment');
 $this->_loadedData['general']['shipment_id'] = $shipment->getEntityId();
 }
 return $this->_loadedData;
 }
and in my form's XML i am having a fieldset:
 <fieldset name="general">
 <argument name="data" xsi:type="array">
 <item name="config" xsi:type="array">
 <item name="label" xsi:type="string" translate="true">General</item>
 </item>
 </argument>
 <field name="shipment_id">
 <argument name="data" xsi:type="array">
 <item name="config" xsi:type="array">
 <item name="dataType" xsi:type="string">number</item>
 <item name="label" xsi:type="string" translate="true">Shipment ID</item>
 <item name="formElement" xsi:type="string">hidden</item>
 </item>
 </argument>
 </field>
 ...
 </fieldset>
Anyway, the code above from the DataProvider is working partially, it loads existing data, but when adding, the hidden field has no value. Any idea how to reference a field from a fieldset when adding/editing data?
What should be the structure of $this->_loadedData when adding/editing data?
1 Answer 1
You can set a default value like this:
$this->_loadedData['']['general']['shipment_id'] = $shipment->getEntityId();
$this->_loadedData is indexed by the entity's id. A new entity doesn't have yet an id, so whatever is set in $this->_loadedData[''] it will be loaded for new entities.
Explore related questions
See similar questions with these tags.
importsin the XML, you will get dynamic value if the field you want to get is observable devdocs.magento.com/guides/v2.4/ui_comp_guide/concepts/…