dile-ajax-form
The dile-ajax-form component is designed to create a form that can be automatically submitted via Ajax to the server, without the need to program the HTTP connections.
For its operation, dile-ajax-form simply needs to be configured with the appropriate attributes and define the form body in the component's slot.
Installation
npm i @dile/crud
Usage
Import the dile-ajax-form component.
import '@dile/crud/components/ajax-form/ajax-form.js';
Use the component.
<dile-ajax-form
operation="insert"
endpoint="api/countries"
actionLabel="Save"
>
<demo-country-form id="form"></demo-country-form>
</dile-ajax-form>
dile-ajax-form Requirements
For dile-ajax-form to work correctly, the form component provided in the slot needs to have some basic functionalities:
- Allow assigning values to the form fields.
- Allow obtaining a data object with the values of the form fields.
- Display validation errors.
All these functionalities are achieved by applying a mixin to the form found in the @dile/ui package called DileForm.
You can read the documentation of the DileForm mixin for more information.
Properties
- operation: String, can have two possible values: "insert" or "update".
- endpoint: String, the URL of the web service with the resource to be inserted or edited.
- actionLabel: String, the text that will appear on the form submission button.
- data: Object, the data object that will be sent to the endpoint, which is automatically obtained by querying the form fields.
- relatedId: String, the identifier of the record to be edited. This is only used in the case of an update operation.
- loadOnInit: Boolean, indicates whether the form should automatically load and display the data of the record with the ID specified in
relatedId. - buttonSmall: Boolean, where a value of
trueindicates that the button should be smaller. - formIdentifier: String, the identifier (ID attribute) of the form element provided in the slot, which contains the fields from which data will be retrieved or displayed. The default value is "form".
- setDataOnInit: Boolean, if
true, indicates that the component should use the object provided in thedataproperty to populate the form fields upon initialization. This can be useful when you have an insert form that you want to prepopulate with specific values in the form fields. - responseAdapter: An object with a series of methods used to adapt the response data from the API used by the form. See the configuration section below for more details.
- language: String, the feedback messages language. Available 'en', 'es'. Fallback to 'en'.
- sendDataAsFormData: Boolean, default false. If sendDataAsFormData property is set to true, the
dile-ajax-formcomponent will send a formData object to the server instead of a JSON object. - showCancelButton: Boolean, default false. If true, this componente renders a cancel button. If the cancel button is pressed the component will dispatch a
form-canceledcustom event. - inline: When this property is set to true, the form is displayed inline (in a row).
- actionIcon: Object with an icon template (used the same way as the
iconproperty in thedile-iconcomponent). If defined, the icon is shown instead of the submit button. - cancelIcon: Object with an icon template (used the same way as the
iconproperty in thedile-iconcomponent). If defined, the icon is shown instead of the cancel button. - disableClearAfterInsert: Boolean, if set to
true, the form will retain its input values after a successful insert operation. See additional details in the "Form cleanup after insert operations" section below.
Methods
- loadData(): Loads the data of the item to be edited. The identifier of the item must be specified in the corresponding
relatedIdproperty. - doAction(): Performs the form submission operation as if the form submission button had been clicked.
- clearErrors(): Clears all validation errors that the form or the component itself is displaying.
- clearFeedback(): Clears the feedback messages that the form is displaying. This does not include the feedback messages of the form elements.
- initData(): Sends the values from the object stored in the component's
dataproperty to the corresponding form fields. - clearForm(): Clear the form data.
Custom Events
- dile-ajax-form-get-error: This event is dispatched when the form encounters an error while receiving data from the server that it needs to display in its fields, based on the item being edited. The detail will be the full server response received via Ajax.
- dile-ajax-form-loaded: This event is dispatched when the form has successfully finished loading the data of the resource to be edited. The detail has two properties:
data, containing the value evaluated as the loaded data, andpreviousDetail, providing the full server response detail, including all originally received fields. - save-error: This event is dispatched when errors are encountered while saving data in the form. The detail contains three pieces of data:
msg, with the server's message;validationErrors, with the captured validation errors object; andpreviousDetail, with the complete Ajax response from the server. - save-success: This event is dispatched when the form has been successfully saved. The detail sends three properties:
data, with the evaluated data from the response;msg, with the server's response message; andpreviousDetail, with the complete Ajax response from the server. - form-canceled: This event is dispatched when the cancel button is pressed. The form data is located in the event
detail.dataand a booleandetail.isDirtyform state property.
The component is based on
dile-ajax, so you can also listen for the custom events documented in that component.
CSS Custom Properties
You can customize the form using these CSS Custom Properties.
| Custom property | Description | Default |
|---|---|---|
| --dile-ajax-form-actions-margin-top | Margin top on the action button | 1rem |
| --dile-form-actions-gap | Gap between action buttons | 1.2rem |
| --dile-form-actions-justify-content | Flex justify content for action buttons | flex-start |
| --dile-ajax-form-cancel-button-background-color | Cancel button background color style | transparent |
| --dile-ajax-form-cancel-button-text-color | Cancel button text color style | #303030 |
| --dile-ajax-form-cancel-button-border-color | Cancel button border color style | transparent |
| --dile-ajax-form-cancel-button-hover-background-color | Cancel button hover background color style | transparent |
| --dile-ajax-form-cancel-button-hover-text-color | Cancel button hover text color style | #303030 |
| --dile-ajax-form-cancel-button-hover-border-color | Cancel button hover border color style | #303030 |
| --action-icon-color | Color of submit icon button when actionIcon property is defined | --dile-primary-color or #674cdc |
| --cancel-icon-color | Color of cancel icon button when cancelIcon property is defined | #d74c3c |
| --inline-gap | Gap between form and action button when form is inline | 1rem |
Attributes for Styling
- hiddefeedback: When this attribute is set, the form does not display feedback messages. The
displayCSS property of the feedback element is set tonone.
Configuration
The dile-form-ajax component is designed to adapt to different types of APIs and websites. It can define various types of requests and handle different types of responses.
Customize the HTTP request
The dile-ajax-form component uses dile-ajax under the hood to make the request to the server. In turn, dile-ajax uses Axios as the library for HTTP connections.
If you need to customize how dile-ajax-form uses Axios to make Ajax connections to the server, please refer to the documentation for dile-ajax.
Response Configuration
The dile-ajax-form component sends and receives data via HTTP requests to a REST API. To extract the necessary data in each case, the API uses a default behavior that works with typical REST APIs.
To customize the component's behavior, allowing it to adapt to any type of API response, you can pass a custom adapter using the responseAdapter property.
<dile-ajax-form
operation="insert"
endpoint="customized-api/users"
.responseAdapter=${customizedResponseAdapter}
>
<resource-form id="form"></resource-form>
</dile-ajax-form>
You can find more information on how to create custom adapters on the Response Adapter page.
Form Cleanup After Insert Operations
By default, forms are automatically cleared after a successful insert operation. This behavior ensures a clean state for subsequent insertions and avoids unintentional re-submissions of the same data.
Preventing Automatic Cleanup
If you wish to retain the form's data after an insert operation, you can use the disableClearAfterInsert property. Setting this property to true prevents the automatic cleanup and keeps the form's current values intact.
Implementing Custom Cleanup
For scenarios requiring a tailored cleanup process, you can override the clearData() method in the form provided via the slot to the dile-ajax-form component. This method is responsible for clearing the form's fields and is invoked automatically when cleanup is required.
The clearData() method is inherited by the form when it applies the DileForm mixin. The default implementation performs a generic cleanup of the form fields. However, you can override it in your custom forms to implement specific behaviors as needed.
Example: Overriding clearData()
import { LitElement } from 'lit';
import { DileForm } from '@dile/ui/mixins/form';
class CustomForm extends DileForm(LitElement) {
clearData() {
this.shadowRoot.querySelector('#specificField').value = '';
}
}
customElements.define('custom-form', CustomForm);
This flexibility allows you to adapt the cleanup behavior to match your application's requirements.
dile-ajax demos
Form Component used on dile-ajax-form
Before we start looking at the demos of dile-ajax-form, let's include an example of a form that uses the DileForm mixin. This mixin provides all the necessary functionality for easy integration with dile-ajax-form.
<script type="module">
import { LitElement, html, css } from 'lit';
import '@dile/ui/components/input/input.js';
import '@dile/ui/components/select/select.js';
import { DileForm } from '@dile/ui/mixins/form'
export class DemoCountryForm extends DileForm(LitElement) {
static styles = [
css`
:host {
display: block;
}
`
];
render() {
return html`
<dile-input label="Country name" name="name" id="name" hideErrorOnInput></dile-input>
<dile-input label="Slug" name="slug" id="slug" hideErrorOnInput></dile-input>
<dile-select name="continent" id="continent" label="Continent" hideErrorOnInput>
<select slot="select">
<option value="">Select...</option>
<option value="Europe">Europa</option>
<option value="South America">América del Sur</option>
<option value="North America">Norte América</option>
<option value="Asia">Asia</option>
<option value="Africa">Africa</option>
<option value="Oceania">Oceania</option>
</select>
</dile-select>
`;
}
}
customElements.define('demo-country-form', DemoCountryForm);
</script>
<demo-country-form></demo-country-form>
Insert Ajax demo
<script type="module">
import '@dile/crud/components/ajax-form/ajax-form.js';
</script>
<dile-ajax-form
id="ajaxelement"
operation="insert"
endpoint="https://timer.escuelait.com/api/countries"
actionLabel="Save"
>
<demo-country-form id="form"></demo-country-form>
</dile-ajax-form>
Update form example
<dile-ajax-form
id="ajaxupdate"
operation="update"
relatedId="1"
loadOnInit
endpoint="https://timer.escuelait.com/api/countries"
actionLabel="Save"
>
<demo-country-form id="form"></demo-country-form>
</dile-ajax-form>
dile-components