1.12.0 • Published 3 years ago

curotec-form-mixin v1.12.0

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

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.

MethodParametersDescriptionParent Method
showModalMethod which opens up the modal
hideModalMethod to close the modal
listPageMethod to navigate to list page from add/edit page
fetchFormDataMethod which fetches the initial data for the add/edit forms from the backend
formBeforeFetchDataMethod which can be used to add more functionality before fetchformData method sends request to the backendfetchFormData
formFetcheddataMethod gets executed once the fetchFormData function gets response from the serverfetchFormData
onSubmitMethod handles the functionality when submit button gets clicked
formBeforeSubmitMethod which sends response as boolean to proceed the onSubmit MethodonSubmit
finalSubmitMethod send the form data to the backend and handles its responseonSubmit
formSubmittedresponseSuccess Method for the finalSubmit Method. This method can be used to proceed the final functionality once the server response is successfinalSubmit
formSubmittedCallbackresponseCallback method for the form submitted methodformSubmitted
formSubmittedRedirectresponseMethod used to redirect once the add/edit form is successfully saved in the backendformSubmitted
formSubmittedErrorresponseMethod which catches the error which gets rejected from the serverformSubmitted
downloadFilefileIdThis method allows the user to download the file from the server. Desired File Id is the parameter for this method
getShowFileUrlimgThis method allows the user to view the file from the server.
1.12.0

3 years ago

1.11.0

3 years ago

1.10.0

3 years ago

1.9.1

3 years ago

1.9.0

3 years ago

1.8.0

3 years ago

1.7.0

3 years ago

1.6.0

3 years ago

1.5.0

3 years ago

1.4.0

3 years ago

1.3.0

3 years ago

1.2.0

3 years ago

1.1.0

3 years ago

1.0.0

3 years ago