vue js checkbox state not updated - javascript

Hey iam writing piece of code in vue.js. I have problem with checkboxes. I have two of them and they are connected with my backend. They look like this:
<b-form-checkbox
v-model="selectedUser.institutionPersonRelations[0].communicationBlocked" #change="editBlockOfCommunication({institutionId:selectedUser.institutionPersonRelations[0].id, profileId:selectedUser.id})">
</b-form-checkbox>
<b-form-checkbox v-model="selectedUser.institutionPersonRelations[0].uploadBlocked" #change="editUploadBlock({institutionId:selectedUser.institutionPersonRelations[0].id, profileId:selectedUser.id})" :disabled="selectedUser.institutionPersonRelations[0].communicationBlocked == true">
</b-form-checkbox>
Everything working correctly until i check second checkbox and then check first checkbox and then uncheck first checkbox. First changing value X and Y in database. Second changing value Y in database. In this case database in updated correctly but second checkbox even if is set to false is still checked, and i need to reload the page to update it.
My backend in php is hit on change event on checkbox looks like that
public function editBlockOfCommunicationForProfile(int $institutionPersonId, int $profileId): void
{
$entityManager = $this->ormGateway->getEntityManager();
$profile = $entityManager->find(ProfileDto::class, $profileId);
if ($profile !== null) {
$institutionProfile = $profile->getInstitutionPersonRelationWithGivenId($institutionPersonId);
if ($institutionProfile !== null) {
if (!$institutionProfile->getDeactivated()) {
if ($institutionProfile->getCommunicationBlocked() === false) {
$institutionProfile->setCommunicationBlocked(true);
$institutionProfile->setUploadBlocked(true);
}
else {
$institutionProfile->setCommunicationBlocked(false);
$institutionProfile->setUploadBlocked(false);
}
}
}
}
$entityManager->flush();
}
/**
* #param int $institutionPersonId
* #param int $profileId
*/
public function editUploadBlockForProfile(int $institutionPersonId, int $profileId): void
{
$entityManager = $this->ormGateway->getEntityManager();
$profile = $entityManager->find(ProfileDto::class, $profileId);
if ($profile !== null) {
$institutionProfile = $profile->getInstitutionPersonRelationWithGivenId($institutionPersonId);
if ($institutionProfile !== null) {
if (!$institutionProfile->getDeactivated()) {
if($institutionProfile->getCommunicationBlocked() === false) {
if ($institutionProfile->getUploadBlocked() === false) {
$institutionProfile->setUploadBlocked(true);
} else {
$institutionProfile->setUploadBlocked(false);
}
}
}
}
}
$entityManager->flush();
}

Related

how can check two condition simultaneity in vue js

I am trying to check if attachment exist in request and attachment field not exist in form it show message in modal and same if body text exist in request and rich text field not exist in form it show error,
but in my case if attachment exist in request and attachment field is exist exist it continue and move to else if but rich text field not exist in form and it not show error because it not execute the if inside the if. I don't know how can i check both condition.
if (this.selectedForm) {
let attachmentField = this.selectedForm.formFields.filter(formField => {
return formField.fieldAttributeType == 'attachment'
})
let descriptionField = this.selectedForm.formFields.filter(formField =>{
return formField.fieldAttributeType == 'rich_text'
})
debugger
if (this.request.attachments.length > 0 && attachmentField.length == 0) {
debugger
this.missingFields.push("Attachment field does't exist in custom form");
if (this.request.bodyText.length > 0 && descriptionField.length == 0) {
this.missingFields.push("and Rich_text field does't exist in custom form");
}
this.$refs.ticketCreationConfirmation.open();
} else if (this.missingFields.length == 0){
this.addRequest(this.request);
}
}
if (this.selectedForm) {
let attachmentField = this.selectedForm.formFields.filter(formField => {
return formField.fieldAttributeType == 'attachment'
})
let descriptionField = this.selectedForm.formFields.filter(formField => {
return formField.fieldAttributeType == 'rich_text'
})
if (this.request.attachments.length > 0 && attachmentField.length == 0) {
this.missingFields.push("Attachment field doesn't exist in custom form");
}
if (this.request.bodyText.length > 0 && descriptionField.length == 0) {
this.missingFields.push("Rich_text field doesn't exist in custom form");
}
if (this.missingFields.length > 0) {
this.$refs.ticketCreationConfirmation.open();
} else {
this.addRequest(this.request);
}
}
You can then join the error messages like that if you want to display them joined with "and":
this.missingFields.join(" and ");

Filtring cards in React using checkbox onChange

this is my first project using React.js, I want to filter the restaurants cards using checkbox when it it check it show only the restaurants cards with these filters or types true such as the music and WIFI. The problems are it show the default cards perfectly but after I checked the checkbox it's change the all type or filters values into false such as Music and WIFI instead of create or map only the cards that false. In addition, it will not create the default cards after double check, can you please help me
The code:
import React, { Component } from 'react';
import axios from 'axios';
import App from "../App";
import Cards from "../Card";
function CreateCards(resturants) {
//Handel the Music, Wifi, Partition (to transfer it from bolean form into string)
if (resturants.Music == true){
resturants.Music = "Music";
}else{
resturants.Music = "No Music";
}
if (resturants.Wifi == true){
resturants.Wifi = "Wifi";
}else{
resturants.Wifi = "No Wifi";
}
if (resturants.Partition == true){
resturants.Partition = "Partition";
}else{
resturants.Partition = "No Partition";
}
return(
<Cards
key={resturants._id} // done
theCardId={resturants._id} // done
placeName={resturants.Name} // done
stars={resturants.Rating} // done
PRating={resturants.PRating} //until filters
music= {resturants.Music} // done
img={resturants.icon} // need uploads file
status={Status(resturants.OpenTime, resturants.CloseTime)} // done
descreption={resturants.Description} // done
wifi={resturants.Wifi} // done
partition={resturants.Partition} // done
/>
);
}
// Check if the place is open or closed depending on the work hours
function Status (Open, Close){
const date = new Date();
var hours = date.getHours();
const red = 'red';
const green = 'green';
if ((Open <= hours) && (hours < Close)){
// console.log("Open");
return "Open";
}else{
// console.log("Close");
return "Close";
}
}
export default class Resturants extends Component {
//constructor elemnts in login
constructor(props){
super(props);
//intialy no data enterd
this.state = {
resturants: [],
filter: ""
}
this.Filtering = this.Filtering.bind(this);
}
componentDidMount(){
//Get Resturants data
axios.get('http://localhost:3000/places')
.then(resp => {
console.log(resp)
this.setState({
resturants: resp.data
})
})
}
Filtering(e){
// this.setState({filter:e.target.value});
e.preventDefault();
this.state.resturants.filter(Type => {
// console.log(Type.Music === true);
})
}
render(){
return(
<div className="flexthem">
<div className="Filters">
<h4>Filters</h4>
<input className="Checkbox" type="checkbox" id="Type1" value="" onClick={this.Filtering}></input>
</div>
<div className="general-card">
{this.state.resturants.map(CreateCards)}
</div>
</div>
);
}
}
a bit of advice.
use "==="
use function componented.
the hook "useState" is a lot simpler than class component state.
restraunt.music = "music"
is a string.
and
restaurant.music = true
is a boolean.
if you set a variable as a string and try to check if it is false or true after. It will return undefined. If it is an empty string, it will return false.
if (resturants.Music == true){
resturants.Music = "Music";
}else{
resturants.Music = "No Music";
}
in react when you set or change the state, then it refreshes. If you are changing the state with this, you are going to put it through he if statement again. It will return undefined and then not change the checkboxes from their default value.

Angular Custom Validator Doesn't Reflect Changes in View

I have custom validator like this:
export class PasswordValidator {
static MatchPassword(AC: AbstractControl) {
const formGroup = AC.parent;
if(formGroup) {
let password = formGroup.value.password // to get value in input tag
let confirmPassword = formGroup.value.confirmPassword; // to get value in input tag
if(password != confirmPassword) {
formGroup.get('confirmPassword').setErrors({ matchPassword: true });
} else {
formGroup.get('confirmPassword').setErrors(null);
}
console.log(formGroup.get('confirmPassword').errors);
} else {
return null
}
}
}
And i have added to the form:
this.registerationForm.addControl("confirmPassword", new FormControl('', Validators.compose([Validators.required, PasswordValidator.MatchPassword])));
And in View:
<ion-item class="error-message" *ngIf="registerationForm.controls.confirmPassword.hasError('matchPassword')
&& registerationForm.controls.confirmPassword.touched">
<p>Some message*</p>
</ion-item>
But the problem is i can see the console window but i don't see it reflects in view. The ngIf condition isn't showing the error message
Use detectChanges() when you've updated the model after angular has run it's change detection, or if the update hasn't been in angular world at all.
Use markForCheck() if you're using OnPush and you're bypassing the ChangeDetectionStrategy by mutating some data or you've updated the model inside a setTimeout;
export class PasswordValidator {
static MatchPassword(AC: AbstractControl) {
const formGroup = AC.parent;
if(formGroup) {
let password = formGroup.value.password // to get value in input tag
let confirmPassword = formGroup.value.confirmPassword; // to get value in input tag
if(password != confirmPassword) {
formGroup.get('confirmPassword').setErrors({ matchPassword: true });
} else {
formGroup.get('confirmPassword').setErrors(null);
}
console.log(formGroup.get('confirmPassword').errors);
this.ref.markForCheck();
} else {
return null
}
}
}
add this.ref.markForCheck(); after you update the form.

JavaScript Model Form Validation

I am using BackboneJS MVC pattern and have a form with 2 fields which the user can select.
I call changeAction whenever there is any change in selection by the user (to call validation);
changeAction: function (event) {
var self = this;
var target = event.target;
target.value = $.trim(target.value);
change[target.name] = target.value;
this.model.set(change);
var check = self.model.validateItem(target.id);
if (check.isValid === false) {
self.addValidationError(target.id, check.message);
} else {
self.removeValidationError(target.id);
}
}
My validation is defined in the Model as below;
this.validators.myDropDownField = function(value) {
return !_.isUndefined(value) && !_.isNull(value) && $.trim(value).length > 0 ? {
isValid: true
} : {
isValid: false,
message: "Select dropdown field"
};
};
validateItem: function(key) {
var result = (this.validators[key]) ? this.validators[key](this.get(key)) : {
isValid: true
};
return result;
}
Now my question is I do not want to do anything to the Model in changeAction.
But if I remove the line this.model.set(change) in changeAction()
the validation does not work correctly. I do not get the value in the function
this.validators.myDropDownField
How do I handle this ?

Dynamic form validation with ASP variables

I have 52 members in my database. When displayed in the admin panel, each one has a form associated with it so I can make notes for each member.
Each Member has an ID so I name each form on the page like this: "frmRepNotes<%=MemberList("MemberID")%>" based on the memberID from the database. This results in something like frmRepNotes67453. I now want to validate the form before saving the notes.
How can I use that number in the JavaScript?
function validate(strid)
{
var ErrorFound = 0
if (document.'+strid+'.taNotes.value == '')
{
ErrorFound = ErrorFound + 1
}
if (ErrorFound == 0)
{
document.'+strid+'.submit();
}
}
How can this be done?
Consider refactoring to be something like this?
function validate(strid)
{
var ErrorFound = 0;
var theForm = document.getElementById("frmRepNotes"+strid);
if (theForm.taNotes.value == '')
{
ErrorFound +=1;
}
if (ErrorFound == 0)
{
theForm.submit();
}
}

Categories