curotec-form-mixin v1.12.0
curotec-form-mixin
A collection of mixin for form handling in vue or nuxt.
Install
npm i curotec-form-mixin
Configuration (Optional)
The default redirection url for unauthenticated user from backend response is '/login'.
The default status code from the server response for Unauthenticated user is 401 and for Unauthorized access is 403.
These url and response code can be configured in the .env file if any custom status code or custom url for login is followed in the backend server.
The below are the env variables which can be used to override the default values.
# Curotec Form Mixin variables
CU_UNAUTHENTICATED_CODE=401
CU_UNAUTHORIZED_CODE=403
CU_REDIRECT_IF_UNAUTHENTICATED=/login
CU_UNAUTHENTICATED_CODE - To configure the custom status code from serve for the unauthenticated user
CU_UNAUTHORIZED_CODE - To configure the custom status code from serve for the unauthorized access
CU_REDIRECT_IF_UNAUTHENTICATED - To configure the custom redirection url if the user is not authenticated
Usage
Frontend Example
<!-- within the component -->
<!-- bootstrap-vue field example -->
<template>
<div>
<b-form-group
class="required-input"
label="Name"
:invalid-feedback="form.errors.get('name')"
:state="form.errors.state('name')"
>
<b-input-group>
<b-form-input
v-model.trim="form.name"
:state="form.errors.state('name')"
>
</b-form-input>
</b-input-group>
</b-form-group>
</div>
</template>
<!-- global component field example -->
<InputText
model="name"
label="Name"
:form="form"
:required="true"
></InputText>
<script>
import formMixin from "curotec-form-mixin";
...
...
export default {
name: '....',
mixins: [formMixin],
data() {
return {
resourceURL: "invoices", //This is the resource url for the backend resource controller
form: {
name: ''
}
}
}
}
</script>
Note: The form object can be initialized in the data method in frontend, or it can be sent from the respective function from backend of the project.
File Example
Upload Example
<!-- bootstrap-vue file field example -->
<b-form-group
:invalid-feedback="form.errors.get('fileKey')"
:state="form.errors.state('fileKey')"
class="required-input"
label="File"
>
<b-form-file
accept="image/jpeg, image/png, image/gif, application/pdf, ...."
id="file-upload"
v-model="form.fileKey"
:state="form.errors.state('fileKey')"
placeholder="File"
></b-form-file>
</b-form-group>
<!-- global file upload component example -->
<FilesComponent
:model="'thumbnails'"
:form="form"
:form-model="formModel"
></FilesComponent>
Download/View File Example
<!-- Download File Button -->
<b-link @click.prevent="downloadFile(file.id)">
<i class="fas fa-file-download"></i> {{ file.name }}
</b-link>
<!-- View File Link -->
<!-- File collection is the parameter to be passed into the getShowFileUrl method -->
<a :href="getShowFileUrl(file)" target="_blank">
<i class="fas fa-eye"></i> {{ file.name }}
</a>
<script>
...
methods: {
downloadFile(fileId) {
let url = "documents/download/" + fileId;
if (!(typeof fileId === 'number' && isFinite(fileId))) {
url = fileId;
}
this.$axios.get(url).then((response) => {
let token = this.$auth.getToken('local');
token = "?token=" + token.replace("Bearer ", "");
let link = document.createElement("a");
link.href = response.data + token;
link.setAttribute("target", "_blank");
link.click();
});
}
}
</script>
Note: downloadFile method is a inbuilt method in package which can be overridden. By default, the package uses the "documents/download/" + fileId
url for downloading the file. Kindly define this url in backend which handles the file download functionality.
Backend Example
## Within the validation request file
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return [
"name" => 'required',
];
}
/**
* Get custom attributes for validator errors.
*
* @return array
*/
public function messages(): array
{
return [
"name.required" => 'The name field is required',
];
}
/**
* Store a newly created resource in storage.
*
* @param CustomRequestFile $request
* @return Response
*/
public function store(CustomRequestFile $request)
{
try {
$data = $request->validated();
} catch (\Exception $exception) {
return $this->apiExceptionResponse($exception);
}
}
//Backend response if validation fails
// Response code : 422 (by default. If it changes, kindly configure in .env file of frontend)
{
"message": "The given data was invalid.",
"errors": {
"name": [
"The name field is required."
]
}
}
The above response will be handled by the package and the message gets shown in toaster and field gets highlighted with the respective error in the below
Form Resource - Backend
The form data can be created and sent from the create function of the resource controller from backend of the project. The create function can be used for both add and edit modules.
Resource Controller File
/**
* @param HotelRequest $request
*
* @return mixed
*/
public function create()
{
return response()->json([
...
...
'data' => new UserResource(new User()),
]);
}
API Resource File
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'role' => $this->role,
'formData' => [
'roles' => Role::select('label', 'name as value')->get(),
],
];
}
}
Note: FormData array contains the input values required in the form fields.
For example:
While creating/editing a user, we may require to select the role for that user in a dropdown. So to preload the role data in that dropdown, we are sending the options in formData.
In the frontend, we need to assign the apt formData key into the options attribute of dropdown which is shown in the below code example:
<div class="col-md-6">
<v-select
v-model="form.role"
class="form-control"
placeholder="Please select role"
:reduce="(role) => role.value"
:options="form.formData.roles"
multiple
/>
</div>
Methods
Methods available on the form-mixin.
Method | Parameters | Description | Parent Method |
---|---|---|---|
showModal | Method which opens up the modal | ||
hideModal | Method to close the modal | ||
listPage | Method to navigate to list page from add/edit page | ||
fetchFormData | Method which fetches the initial data for the add/edit forms from the backend | ||
formBeforeFetchData | Method which can be used to add more functionality before fetchformData method sends request to the backend | fetchFormData | |
formFetched | data | Method gets executed once the fetchFormData function gets response from the server | fetchFormData |
onSubmit | Method handles the functionality when submit button gets clicked | ||
formBeforeSubmit | Method which sends response as boolean to proceed the onSubmit Method | onSubmit | |
finalSubmit | Method send the form data to the backend and handles its response | onSubmit | |
formSubmitted | response | Success Method for the finalSubmit Method. This method can be used to proceed the final functionality once the server response is success | finalSubmit |
formSubmittedCallback | response | Callback method for the form submitted method | formSubmitted |
formSubmittedRedirect | response | Method used to redirect once the add/edit form is successfully saved in the backend | formSubmitted |
formSubmittedError | response | Method which catches the error which gets rejected from the server | formSubmitted |
downloadFile | fileId | This method allows the user to download the file from the server. Desired File Id is the parameter for this method | |
getShowFileUrl | img | This method allows the user to view the file from the server. |