How to deal with a form that the button submit placed in parent component - react-hook-form

I use react hook form, i have a form which my submit button placed in the parent component. my question is how i deal with the loading state of the button, when i try to call an api?. I have tried to use isSubmitting state, but again i dont know how to make that state visible for another component. i am glad to receive an answer. my real problem is how i can make state 'isSubmitting' able to read by my parent component, so i can do loading button after i call the api.
this for the parents
const ForceEditPassword = () => {
const childRef = useRef<any>();
return (
<>
<div className='force-edit-password d-flex flex-column justify-content-center align-items-center'>
<div className='inner d-flex justify-items-center align-items-center flex-column'>
<FormEditPassword ref={childRef} />
<button className='bg-primary rounded bottom-0 start-50 translate-middle-x'
onClick={() => { childRef.current?.onSubmit(); }}>
<p className='text-light m-0 p-2 text-capitalize rounded'>
Simpan
</p>
</button>
</div>
</div>
</>
);
};
export default ForceEditPassword;

Related

Toggle Modal From Another Modal with Javascript

Issue
Toggling a modal with Javascript from another modal creates a conflict with the .modal-backdrop. Solutions I have thought of require me to make some functions to count .modal-backdrop but it breaks Bootstrap's native modal-dismiss behavior. I think maybe there could be better way that incorporates Bootstrap's native CSS (fade, etc.) without additional functions?
Here is my current working example
Ultimate Goal
Create a modal that can toggle another modal while retaining Bootstrap's default CSS. Also eliminate .modal-backdrop from creating more than one instance.
Background
I am creating a "parent" form that can be built dynamically (with JQuery) based on user input. Two sections of the form, "Add System" and "Add Circuit", will require an additional "child" form that will be placed inside a modal, outside the scope of the parent form (This helps avoid nesting one form inside the parent form). The reason I want to separate the user inputs from the parent and child forms is because the child form inputs may have different JQuery validation rules than the parent form (i.e., the data is not required to create a CSD, but if you want to add a system/circuit then I want to make sure you give me all the necessary data to create those objects). If a user wants to Add a system or a circuit:
they click the "Add System/Circuit" button where the 1st modal appears.
The user is prompted with a form to search for an existing one or create a new one.
If the user decides to "Add New System/Circuit", then a different modal appears.
The user is prompted with a form to enter the relevant data.
Here is my javascript function creating the modals. I am generating the modal dynamically based on the option the user chooses. One thing to note, since I am creating these modals in the same function, I want to make sure my function deletes the existing modal content too. (That's why I added the line
if (modalWrap !== null) {
modalWrap.remove()
}
at the beginning of my function)
var modalWrap = null
function create_dynamic_csd_modal(modal_type, section_type) {
if (modalWrap !== null) {
modalWrap.remove()
}
modalWrap = document.createElement("div")
if (modal_type == "new") {
if (section_type == "system") {
var modalContent = `
<div class="modal-header">
<h1 class="modal-title">Add New System</h1>
</div>
<div class="modal-body" style="height: 50vh;">
[...]
</div>
`
} else if (section_type == "circuit") {
var modalContent = `
<div class="modal-header">
<h1 class="modal-title">Add New Circuit</h1>
</div>
<div class="modal-body" style="height: 50vh;">
[...]
</div>
`
}
modalWrap.innerHTML = `
<div class="modal fade csd-add-new-${section_type}" tabindex="-1">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
<div class="modal-content">
<form
action='/ajax/csd_add_new_${section_type}/'
method='POST'
class="csd-add-new-${section_type}"
novalidate
>
${modalContent}
<div class="modal-footer">
<button
class="btn btn-warning cancel"
type="reset"
data-bs-dismiss="modal"
>
Cancel
</button>
<button
class="btn btn-secondary previous"
type="button"
>
Previous
</button>
<button
class="btn btn-danger"
type="button"
>
Add
</button>
</div>
</form>
</div>
</div>
</div>
`
} else {
if (section_type == "system") {
var modalContent = `
<div class="modal-body mt-4">
[...]
</div>
`
} else if (section_type == "circuit") {
var modalContent = `
<div class="modal-body mt-4">
[...]
</div>
`
}
modalWrap.innerHTML = `
<div class="modal fade csd-add-existing-${section_type}" tabindex="-1">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<form
action='/ajax/csd_add_existing_${section_type}/'
method='POST'
class="csd-add-existing-${section_type}"
novalidate
>
${modalContent}
<div class="modal-footer">
<button
class="btn btn-warning cancel"
type="reset"
data-bs-dismiss="modal"
>
Cancel
</button>
<button
class="btn btn-danger"
type="submit"
>
Add
</button>
</div>
</form>
</div>
</div>
</div>
`
}
document.body.append(modalWrap)
var modal = new bootstrap.Modal(modalWrap.querySelector(".modal"))
modal.show()
if ($(".modal-backdrop").length >= 1) {
$(".modal-backdrop").not(":first").remove()
}
}
$(document).on(
"click",
"form.create-csd-series button.add-system, form.create-csd-series button.add-circuit, form.csd-add-existing-system button.add-system, form.csd-add-existing-circuit button.add-circuit",
function(e) {
var button = this
var modal_type = null
if (button.classList.contains("add-system")) {
var section_type = "system"
} else if (button.classList.contains("add-circuit")) {
var section_type = "circuit"
}
if (button.closest(".modal") !== null) {
modal_type = "new"
}
create_dynamic_csd_modal(modal_type, section_type)
},
)
The idea is once the data inside the "child" form is entered and the user clicks "Add" in the modal - the data from this form will populate the parent form in a consolidated view. All the inputs' attributes (like name='some_input_name', id='some_input_id', etc.) from the child form will be transposed into the parent form that match validation rules for it. The user could then edit/delete that data before submitting the parent form to the server. (something like this).

Angular material cdk drag and drop, how to get target(mouse target) element?

I couldn't find any documentation on how to get the target of dropped element using cdk drag drop.
below is the sample code dragging item from box1 div to Shoppingbasket div. here im expecting target should be box2 div. but I'm receiving Shoppingbasket div.here is the
stackblitz example
HTML
<div cdkDropListGroup>
<div class="example-container">
<h2>Available items</h2>
<div cdkDropList [cdkDropListData]="items" class="example-list" cdkDropListSortingDisabled
(cdkDropListDropped)="drop($event)">
<div id="box1" class="example-box" *ngFor="let item of items" cdkDrag>{{item}}</div>
</div>
</div>
<div class="example-container2">
<h2>Shopping basket</h2>
<div id="Shoppingbasket" cdkDropList [cdkDropListData]="basket" class="example-list"
(cdkDropListDropped)="drop($event)">
<div id="box2" class="example-box1" cdkDragHandle></div>
</div>
</div>
</div>
TS
drop($event){
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, event.previousIndex,event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data,event.container.data,event.previousIndex);
}
}
There's no event.target in the cdk drag and drop events but you can manually add the attribute to the event object when needed like this :
event.target = event.container.element.nativeElement;

Triggering A modal from within a countdown function

I am trying to get a bootstrap modal to be triggered when my jsonwebtoken is close to expiring.
I am able to get the modal to fire via a button on the nav bar, but I cannot get the modal to trigger from the function.
when i try to trigger the modal using this.openRenew(renew); i get an cannot find name renew error,
**** navbar.html
<!-- Renew Token -->
<ng-template #renew let-modal>
<div class="modal-header">
<h4 class="modal-title" id="renewModal">Renew Log In</h4>
<button type="button" class="close" aria-label="Close
(click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Your Session In About To Expire.
For Security Please Confirm Your Password To Continue.
<form>
<div class="form-group">
<label for="password">Password</label>
<input id="password" class="form-control"
placeholder="Password" name="password">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark"
(click)="modal.close('Save click')">Log Back In</button>
</div>
</ng-template>
**** navbar.ts
constructor(
public _auth:AuthService,
public _router:Router,
public modalService: NgbModal) {
this._auth.time.subscribe((now: Date) => {
this.currentTime = now.valueOf();
if(!!this._auth.emToken){
if (!this.timeToRenew || this._auth.emExpTime==null){
console.log('Checking Time to renew',
this._auth.emExpTime*1000-this.currentTime );
if((this._auth.emExpTime*1000)-45000<this.currentTime){
this.timeToRenew = true;
console.log('Time to Log Back In');
/ * Need to trigger openRenew() here *
}
}
}
});
}
openRenew(renew) {
this.modalService.open(renew, {ariaLabelledBy:
'renewModal'}).result.then(
(result) => {
console.log(result);
// validate password
});
}
I've put together a StackBlitz demo to show this working. It should automatically display the modal after around 10 seconds.
There's a couple of changes you'll need to make to your code to get this to work:
i. Make sure you can get a reference to the modal template in your TS file by using the following code to declare the template as a class variable and using #ViewChild to get a reference to it in the HTML:
#ViewChild('renew')
private renew: TemplateRef<any>;
I've modified the logic to make it simpler for the demo - in this example the AuthService fires the time every 5 seconds. The component listens to this and if the timestamp emitted by the AuthService is greater than 10 seconds after the component was created, it displays the modal.
ii. You will need assign the subscription to a variable subscription so that you can then unsubscribe when you open the modal:
// 1. Maintain a reference to the subscription
const subscription: Subscription = this._auth.time.subscribe((now: Date) => {
...
if (/*should renew*/) {
this.openRenew(this.renew);
subscription.unsubscribe(); // 2. Unsubscribe here after opening modal
}
});
This prevents additional modals being displayed on top of the original one every time the AuthService emits a timestamp.

How do I properly handle submit events in Vue + Rails?

I'm learning Rails, Vue and JS and I've got a question on the proper handling of submit buttons on Rails using Vue component to validate it. I'm using mdbootstrap for the styles.
I built a form wizard which uses vee-validate for validating the fields and in some forms I want to perform some server side operations too (eg.: validate exact address with geocoding). I'm currently facing basically three issues.
Although I added a v-clock directive, I'm still seeing a little
flicker every time the form wizard component gets loaded (eg.: page
refresh).
I had to workaround the Rails automatic data-disable-with handling to get it working, and it looks not optimal to me, and I'd like to know if there's a better way to deal with it (I had to disable the submit event propagation and prevent default and do the disabling/enabling manually otherwise the handler from Rails UJS will receive it afterwards and disable the button forever).
Although the button gets enabled again, it gets brighter every time I click on it if validation fails (some handler from mdbootstrap maybe?). It happens only after I click on refresh button on the browser and I've noticed the following div is created after each click followed by an error during form validation, causing the button to become "brighter" as in a accumulated "disabled effect":
Anyone has ideas on how these issues could be solved? Thanks!
new.html.erb:
<div id="stepper">
<div v-cloak>
<transition-group name="fade">
<div class="d-none d-lg-block" key="progress_bar">
<%= render 'forms/progress_bar' %>
</div>
<div id="step1" v-if="step === 1" key="step1">
<%= render 'forms/description' %>
</div>
<div id="step2" v-if="step === 2" key="step2">
<%= render 'forms/address' %>
</div>
</transition-group>
</div>
</div>
_description.html.erb:
<template>
<form
id="description-form"
data-vv-scope="description-form"
novalidate="true"
#submit.prevent="next('description-form', $event)">
<div class="row mb-5">
<div class="col-lg-12 col-md-12">
<div class="container">
<div class="row" id="step-1">
<div class="col-lg-6">
<div class="max-height-80">
<div class="mb-4">
<h4><%= t(:'step1.title') %></h4>
</div>
<div class="form-group">
<label
for="name"
class="control-label">
<%= t(:'step1.label.name') %>
</label>
<input
id="name"
name="name"
type="text"
class="form-control"
placeholder="<%= t(:'step1.input.name') %>"
v-validate="'required'"
v-model="name"
:class="{ 'is-invalid': errors.has('name','description-form') }"
required/>
<div
v-if="errors.has('name','description-form')"
class="invalid-feedback">
<%= t(:'name.required') %>
</div>
</div>
<div class="form-group">
<label
for="description"
class="control-label">
<%= t(:'step1.label.description') %>
</label>
<textarea
id="description"
name="description"
class="form-control"
placeholder="<%= t(:'step1.input.description') %>"
rows="11"
v-validate="'required'"
v-model="description"
:class="{ 'is-invalid': errors.has('description','description-form') }"
required>
</textarea>
<div
v-if="errors.has('description','description-form')"
class="invalid-feedback">
<%= t(:'description.required') %>
</div>
</div>
</div>
<footer class="page-footer white fixed-bottom d-block d-sm-none z-depth-1" id="footer">
<div class="d-flex justify-content-end">
<button class="btn btn-default pull-right" type="submit" data-remote="true" data-disable-with="<%= wait_spinner %>"><%= t(:'btn.next') %></button>
</div>
</footer>
<div class="d-none d-sm-block">
<div class="d-flex justify-content-end mt-2">
<button class="btn btn-default pull-right" type="submit" data-remote="true" data-disable-with="<%= wait_spinner %>"><%= t(:'btn.next') %></button>
</div>
</div>
</div>
<div class="col-lg-2"></div>
<div class="col-lg-4 d-none d-lg-block mt-lg-5">
</div>
</div>
</div>
</div>
</div>
</form>
</template>
stepper.js
var element = document.getElementById("stepper");
if (element != null) {
Vue.use(VeeValidate);
Vue.use(VueResource);
Vue.http.headers.common['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
const stepper = new Vue({
el: element,
data() {
return {
/**
* The step number (starting from 1).
* #type {Integer}
*/
step:1,
name:null,
description:null
}
}
},
methods: {
/**
* Goes back to previous stepp
*/
prev() {
this.step--;
},
/**
* Triggers validation of current step and goes to the
* next step if validation succeeds
* #param {String} scope The step scope used for validation.
* #param {Object} Event that triggered the next step (form submit)
*/
next(scope, event) {
if (event != undefined) {
event.stopImmediatePropagation();
event.preventDefault();
event.stopPropagation();
}
const form = event.currentTarget;
$("button[type=submit]",form).each(function() {
Rails.disableElement(this);
});
this.validateFields(scope, event);
},
validateFields(scope, event) {
this.$validator.validateAll(scope).then(function (valid) {
this.postFieldsValidation(valid, event);
}.bind(this));
},
postFieldsValidation(valid, event) {
if (valid) {
stepper.step++;
}
const form = event.currentTarget;
$("button[type=submit]",form).each(function() {
Rails.enableElement(this);
});
},
handleError(error) {
alert(error)
},
submit() {
}
}
});
}
* edit *
for #3, I'm using a workaround for removing the div with waves-ripple class inside my button when re-enabling elements on the form.
$("div").remove("button .waves-ripple");
however, it would be nice to know the root cause for it.

Dragging file onto document body triggers modal with Dropzone.js

I want to duplicate the behavior for uploading images in Slack in my chat app.
Currently, you can click a button in the area where you enter a message, and that brings up a modal where you can drag and drop files using Dropzone.js. That’s great.
However, I also want the entire page (document body) to be a dropzone as well. So when you drag a file onto the screen, I want the previously mentioned modal to pop up, with the dragged file loaded.
I tried adding this to the bottom of the page, but no dice:
<script>
// Make whole page a dropzone for image uploads
new Dropzone("#body", { // Make the whole body a dropzone
url: "/upload/url", // Set the url
previewsContainer: "#modal-image-uploads .modal-body #previews" // Define the container to display the previews
});
Dropzone.options.filedrop = {
init: function () {
this.on("complete", function (file) {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
$('body').append("<%= escape_javascript(render :partial => 'rooms/modals/image_uploads') %>");
}
});
}
};
</script>
The error in the console is: Uncaught Error: Invalid previewsContainer option provided. Please provide a CSS selector or a plain HTML element.
Here's what the modal looks like:
<div class="modal fade" id="modal-image-uploads" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Upload Image</h4>
</div>
<div class="modal-body">
<div id="previews" class="dropzone-previews"></div>
<form action="/file-upload"
class="dropzone"
id="my-awesome-dropzone"></form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>

Resources