Unable to read the value which is in array inside Model




Asked on July 31, 2020
Hi,

I am using angular 7. I want to fetch the value which is in based on key inside model. But instead of giving it in array it is giving single value when i try to fetch it.
For example:
From the following data I want to fetch the property of value:

{
className: null
colspan: 1
columns: []
currency: undefined
dateDisplayFormat: "D-M-YYYY"
defaultDateFormat: "D-M-YYYY"
defaultDateTimeFormat: "D-M-YYYY hh:mm A"
displayText: undefined
enableFractions: undefined
fieldType: "FormFieldRepresentation"
fields: []
form: FormModel {formService: FormService, taskName: "Nameless task", values: {…}, tabs: Array(0), fields: Array(2), …}
hasEmptyValue: null
hyperlinkUrl: undefined
id: "karnataka"
isValid: (...)
isVisible: true
json: {fieldType: "FormFieldRepresentation", id: "karnataka", name: "Karnataka", type: "multiple-check-box", value: null, …}
maxLength: 0
maxValue: null
minLength: 0
minValue: null
name: "Karnataka"
numberOfColumns: 1
optionType: null
options: []
overrideId: false
params: {existingColspan: 1, maxColspan: 2, customProperties: {…}}
placeholder: null
readOnly: (...)
regexPattern: null
required: (...)
restIdProperty: null
restLabelProperty: null
restResponsePath: null
restUrl: null
roles: undefined
rowspan: 1
tab: null
type: "multiple-check-box"
validationSummary: ErrorMessageModel {message: "", attributes: Map(0)}
value: Array(2)
0: {id: 1, name: "Hubli", checked: true, value: true}
1: {id: 3, name: "Gadag", checked: true, value: true}
length: 2
__proto__: Array(0)
visibilityCondition: undefined
_isValid: true
_readOnly: false
_required: false
_value: Array(2)
0: {id: 1, name: "Hubli", checked: true, value: true}
1: {id: 3, name: "Gadag", checked: true, value: true}
length: 2
__proto__: Array(0)
__proto__: FormWidgetModel
}

for fetching the above i tried with myData.value but it is giving only Hubli instead of whole array. Can anyone please give a solution to this?



Replied on July 31, 2020
Provide more code, how are you fetching value?


Replied on August 01, 2020
@Mukesh My code is as follows:
Please find the code bolded.


import { AlfrescoApiService } from '../../services/alfresco-api.service';
import { LogService } from '../../services/log.service';
import { Injectable } from '@angular/core';
import moment from 'moment-es6';
import { Observable, from, throwError } from 'rxjs';
import { FormFieldModel, FormModel, TabModel, ContainerModel } from '../components/widgets/core/index';
import { TaskProcessVariableModel } from '../models/task-process-variable.model';
import { WidgetVisibilityModel, WidgetTypeEnum } from '../models/widget-visibility.model';
import { map, catchError } from 'rxjs/operators';

@Injectable({
    providedIn: 'root'
})
export class WidgetVisibilityService {

    private processVarList: TaskProcessVariableModel[];
    private form: FormModel;

    constructor(private apiService: AlfrescoApiService,
                private logService: LogService) {
    }
leftVal = [];
actualResult: boolean;
valuesArray=[];
mutiselect = [];
    public refreshVisibility(form: FormModel) {
        this.form = form;
        if (form && form.tabs && form.tabs.length > 0) {
            form.tabs.map((tabModel) => this.refreshEntityVisibility(tabModel));
        }

        if (form) {
            form.getFormFields().map((field) => this.refreshEntityVisibility(field));
        }
    }
    fieldded:FormFieldModel;
    refreshEntityVisibility(element: FormFieldModel | TabModel) {
        if(element instanceof FormFieldModel){
            this.fieldded = element;
        }
        const visible = this.evaluateVisibility(element.form, element.visibilityCondition);
        element.isVisible = visible && this.isParentTabVisible(this.form, element);
    }

    evaluateVisibility(form: FormModel, visibilityObj: WidgetVisibilityModel): boolean {
        const isLeftFieldPresent = visibilityObj && (visibilityObj.leftType || visibilityObj.leftValue);
        if (!isLeftFieldPresent || isLeftFieldPresent === 'null') {
            return true;
        } else {
            return this.isFieldVisible(form, visibilityObj);
        }
    }

    isFieldVisible(form: FormModel, visibilityObj: WidgetVisibilityModel, accumulator: any[] = [], result: boolean = false): boolean {
        const leftValue = this.getLeftValue(form, visibilityObj);
        const rightValue = this.getRightValue(form, visibilityObj);
console.log("left form filed id is:", visibilityObj.leftFormFieldId);
if(visibilityObj.leftFormFieldId){
        let multiCheckBoxType = form.getFieldById(visibilityObj.leftFormFieldId);
       // this.mutiselect = form.getFieldById(visibilityObj.leftFormFieldId);
     if(multiCheckBoxType == undefined){

     }else{
        console.log("multiCheckBoxType===", multiCheckBoxType);
    console.log("fetching type is::", multiCheckBoxType.type);
        console.log("Extracting values from multicheckbox::====", multiCheckBoxType.value);
        console.log("Extracting values from multicheckbox with another way:====", multiCheckBoxType["value"]);
        console.log("leftValue:",leftValue);
        console.log("rightValue:",rightValue);
                const actualResult = this.evaluateConditionForMultipleCheckbox(leftValue, rightValue, visibilityObj.operator);
               console.log("actualResult=======",actualResult); 
                result = actualResult;
        
       
    }
}
          return !!result;
               /**  actualResult;
       // const actualResult = this.evaluateCondition(leftValue, rightValue, visibilityObj.operator);
 //code to make all the visibility fields mandatory
 if(actualResult){
    if(this.fieldded.params.customProperties){
        if(this.fieldded.params.customProperties.visibledRequired){
         form.getFieldById(this.fieldded.id).required= JSON.parse(this.fieldded.params.customProperties.visibledRequired);
        }
    }else{
     form.getFieldById(this.fieldded.id).required= true;
    }
   }else{
        form.getFieldById(this.fieldded.id).required= false;
       if(form.getFieldById(this.fieldded.id).value) {
            form.getFieldById(this.fieldded.id).value = null;
       }
    }
    //code to make all the visibility fields mandatory
        if (this.isValidOperator(visibilityObj.nextConditionOperator)) {
            accumulator.push({ value: actualResult, operator: visibilityObj.nextConditionOperator });
        }

        if (this.isValidCondition(visibilityObj.nextCondition)) {
            result = this.isFieldVisible(form, visibilityObj.nextCondition, accumulator);
        } else if (accumulator[0] !== undefined) {
            result = accumulator[0].value;
            for (let i = 1; i < accumulator.length; i++) {
                if (accumulator[i] !== undefined) {
                    result = this.evaluateLogicalOperation(
                        accumulator[i - 1].operator,
                        result,
                        accumulator[i].value
                    );
                }
            }
        } else {
            result = actualResult;
        }
        return !!result;**/

    }

    getLeftValue(form: FormModel, visibilityObj: WidgetVisibilityModel): string {
        let leftValue = '';
        if (visibilityObj.leftType && visibilityObj.leftType === WidgetTypeEnum.variable) {
            leftValue = this.getVariableValue(form, visibilityObj.leftValue, this.processVarList);
        } else if (visibilityObj.leftType && visibilityObj.leftType === WidgetTypeEnum.field) {
            leftValue = this.getFormValue(form, visibilityObj.leftValue);
            if (leftValue === undefined || leftValue === '') {
                const variableValue = this.getVariableValue(form, visibilityObj.leftValue, this.processVarList);
                leftValue = !this.isInvalidValue(variableValue) ? variableValue : leftValue;
            }
        }
        return leftValue;
    }

    getRightValue(form: FormModel, visibilityObj: WidgetVisibilityModel): string {
        let valueFound = '';
        if (visibilityObj.rightType === WidgetTypeEnum.variable) {
            valueFound = this.getVariableValue(form, visibilityObj.rightValue, this.processVarList);
        } else if (visibilityObj.rightType === WidgetTypeEnum.field) {
            valueFound = this.getFormValue(form, visibilityObj.rightValue);
        } else {
            if (moment(visibilityObj.rightValue, 'YYYY-MM-DD', true).isValid()) {
                valueFound = visibilityObj.rightValue + 'T00:00:00.000Z';
            } else {
                valueFound = visibilityObj.rightValue;
            }
        }
        return valueFound;
    }

    getFormValue(form: FormModel, fieldId: string): any {
        const formField = this.getFormFieldById(form, fieldId);
        let value = undefined;

        if (this.isFormFieldValid(formField)) {
            value = this.getFieldValue(form.values, fieldId);

            if (this.isInvalidValue(value)) {
                value = this.searchValueInForm(formField, fieldId);
            }
        }
        return value;
    }

    isFormFieldValid(formField: FormFieldModel): boolean {
        return formField && formField.isValid;
    }

    getFieldValue(valueList: any, fieldId: string): any {
        let dropDownFilterByName, valueFound;
        if (fieldId && fieldId.indexOf('_LABEL') > 0) {
            dropDownFilterByName = fieldId.substring(0, fieldId.length - 6);
            if (valueList[dropDownFilterByName]) {
                valueFound = valueList[dropDownFilterByName].name;
            }
        } else if (valueList[fieldId] && valueList[fieldId].id) {
            valueFound = valueList[fieldId].id;
        } else {
            valueFound = valueList[fieldId];
        }
        return valueFound;
    }

    private isInvalidValue(value: any): boolean {
        return value === undefined || value === null;
    }

    getFormFieldById(form: FormModel, fieldId: string): FormFieldModel {
        return form.getFormFields().
            find( (formField: FormFieldModel) => this.isSearchedField(formField, fieldId));
    }

    searchValueInForm(formField: FormFieldModel, fieldId: string): string {
        let fieldValue = '';

        if (formField) {
            fieldValue = this.getObjectValue(formField, fieldId);

            if (!fieldValue) {
                if (formField.value && formField.value.id) {
                    fieldValue = formField.value.id;
                } else if (!this.isInvalidValue(formField.value)) {
                    fieldValue = formField.value;
                }
            }
        }
        return fieldValue;
    }

    isParentTabVisible(form: FormModel, currentFormField: FormFieldModel | TabModel): boolean {
        const containers = this.getFormTabContainers(form);
        let isVisible: boolean = true;
        containers.map( (container: ContainerModel) => {
            if ( !!this.getCurrentFieldFromTabById(container, currentFormField.id) ) {
                const currentTab = form.tabs.find( (tab: TabModel) => tab.id === container.tab );
                if (!!currentTab) {
                    isVisible = currentTab.isVisible;
                }
            }
        });
        return isVisible;
    }

    private getCurrentFieldFromTabById(container: ContainerModel, fieldId: string): FormFieldModel {
        const tabFields: FormFieldModel[][] = Object.keys(container.field.fields).map( key => container.field.fields[key]);
        let currentField: FormFieldModel;

        for (const tabField of tabFields) {
            currentField = tabField.find( (tab: FormFieldModel) => tab.id === fieldId );
            if (currentField) {
                return currentField;
            }
        }
        return null;
    }

    private getFormTabContainers(form: FormModel): ContainerModel[] {
        if (!!form) {
            return <ContainerModel[]> form.fields.filter(field => field.type === 'container' && field.tab);
        }
        return [];
    }

    private getObjectValue(field: FormFieldModel, fieldId: string): string {
        let value = '';
        if (field.value && field.value.name) {
            value = field.value.name;
        } else if (field.options) {
            const option = field.options.find((opt) => opt.id === field.value);
            if (option) {
                value = this.getValueFromOption(fieldId, option);
            }
        }
        return value;
    }

    private getValueFromOption(fieldId: string, option): string {
        let optionValue = '';
        if (fieldId && fieldId.indexOf('_LABEL') > 0) {
            optionValue = option.name;
        } else {
            optionValue = option.id;
        }
        return optionValue;
    }

    private isSearchedField(field: FormFieldModel, fieldToFind: string): boolean {
        return (field.id && fieldToFind) ? field.id.toUpperCase() === fieldToFind.toUpperCase() : false;
    }

    getVariableValue(form: FormModel, name: string, processVarList: TaskProcessVariableModel[]): string {
        const processVariableValue = this.getProcessVariableValue(name, processVarList);
        const variableDefaultValue = form.getFormVariableValue(name);

        return (processVariableValue === undefined) ? variableDefaultValue : processVariableValue;
    }

    private getProcessVariableValue(name: string, processVarList: TaskProcessVariableModel[]): string {
        if (processVarList) {
            const processVariable = processVarList.find(
                variable =>
                    variable.id === name ||
                    variable.id === `variables.${name}`
            );

            if (processVariable) {
                return processVariable.value;
            }
        }
        return undefined;
    }

    evaluateLogicalOperation(logicOp: string, previousValue: any, newValue: any): boolean | undefined {
        switch (logicOp) {
            case 'and':
                return previousValue && newValue;
            case 'or' :
                return previousValue || newValue;
            case 'and-not':
                return previousValue && !newValue;
            case 'or-not':
                return previousValue || !newValue;
            default:
                this.logService.error(`Invalid operator: ${logicOp}`);
                return undefined;
        }
    }

    evaluateCondition(leftValue: any, rightValue: any, operator: string): boolean | undefined {
        switch (operator) {
            case '==':
                return leftValue + '' === rightValue + '';
            case '<':
                return leftValue < rightValue;
            case '!=':
                return leftValue + '' !== rightValue + '';
            case '>':
                return leftValue > rightValue;
            case '>=':
                return leftValue >= rightValue;
            case '<=':
                return leftValue <= rightValue;
            case 'empty':
                return leftValue ? leftValue === '' : true;
            case '!empty':
                return leftValue ? leftValue !== '' : false;
            default:
                this.logService.error(`Invalid operator: ${operator}`);
                return undefined;
        }
    }

    cleanProcessVariable() {
        this.processVarList = [];
    }

    getTaskProcessVariable(taskId: string): Observable<TaskProcessVariableModel[]> {
        return from(this.apiService.getInstance().activiti.taskFormsApi.getTaskFormVariables(taskId))
            .pipe(
                map((res) => {
                    const jsonRes = this.toJson(res);
                    this.processVarList = <TaskProcessVariableModel[]> jsonRes;
                    return jsonRes;
                }),
                catchError(() => this.handleError())
            );
    }

    toJson(res: any): any {
        return res || {};
    }

    private isValidOperator(operator: string): boolean {
        return operator !== undefined;
    }

    private isValidCondition(condition: WidgetVisibilityModel): boolean {
        return !!(condition && condition.operator);
    }

    private handleError() {
        this.logService.error('Error while performing a call');
        return throwError('Error while performing a call - Server error');
    }
    //evaluateConditionForMultipleCheckbox
    evaluateConditionForMultipleCheckbox(leftValue: any, rightValue: any, operator: string): boolean | undefined {
        console.log("left val:",leftValue);
        console.log("rightVal=",rightValue);
        console.log("operator=",operator);
       return true;
    }
}




Replied on August 02, 2020
Just before accessing myData.value , use console.log(myData) to check the value of value .


Replied on August 02, 2020
Yes I am checking that         console.log("multiCheckBoxType===", multiCheckBoxType);

It is giving the following result:
className: null
colspan: 1
columns: []
currency: undefined
dateDisplayFormat: "D-M-YYYY"
defaultDateFormat: "D-M-YYYY"
defaultDateTimeFormat: "D-M-YYYY hh:mm A"
displayText: undefined
enableFractions: undefined
fieldType: "FormFieldRepresentation"
fields: []
form: FormModel {formService: FormService, taskName: "Nameless task", values: {…}, tabs: Array(0), fields: Array(2), …}
hasEmptyValue: null
hyperlinkUrl: undefined
id: "karnataka"
isValid: (...)
isVisible: true
json: {fieldType: "FormFieldRepresentation", id: "karnataka", name: "Karnataka", type: "multiple-check-box", value: null, …}
maxLength: 0
maxValue: null
minLength: 0
minValue: null
name: "Karnataka"
numberOfColumns: 1
optionType: null
options: []
overrideId: false
params: {existingColspan: 1, maxColspan: 2, customProperties: {…}}
placeholder: null
readOnly: (...)
regexPattern: null
required: (...)
restIdProperty: null
restLabelProperty: null
restResponsePath: null
restUrl: null
roles: undefined
rowspan: 1
tab: null
type: "multiple-check-box"
validationSummary: ErrorMessageModel {message: "", attributes: Map(0)}
value: Array(2)
0: {id: 1, name: "Hubli", checked: true, value: true}
1: {id: 3, name: "Gadag", checked: true, value: true}
length: 2
__proto__: Array(0)
visibilityCondition: undefined
_isValid: true
_readOnly: false
_required: false
_value: Array(2)
0: {id: 1, name: "Hubli", checked: true, value: true}
1: {id: 3, name: "Gadag", checked: true, value: true}
length: 2
__proto__: Array(0)
__proto__: FormWidgetModel


value is in array only. But if I try to access that it is giving just single value instead of array..
How to get that array? 



Replied on August 02, 2020
I tried this and it is working.

import { Component, OnInit } from '@angular/core';

const myData = {
    roles: undefined,
    rowspan: 1,
    tab: null,
    type: "multiple-check-box",
    value: [
       {id: 1, name: "Hubli", checked: true, value: true},
       {id: 3, name: "Gadag", checked: true, value: true}
    ]
};

@Component({
   selector: 'app-root',
   template: `
       `
})
export class AppComponent implements OnInit  { 
  ngOnInit() {
  console.log(myData.value);
  }
}
   
Use JSON.stringify to understand more the structure of your data.

console.log(JSON.stringify(multiCheckBoxType));








Replied on August 02, 2020
I tried to console console.log(JSON.stringify(multiCheckBoxType));
But I am getting following error:
MultipleCheckBoxComponent.html:16 ERROR TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'NgModuleRef_'
    --- property 'injector' closes the circle
    at JSON.stringify (<anonymous>)



Replied on August 02, 2020
Looks like multiCheckBoxType is HttpResponse object.


Try 
console.log(multiCheckBoxType.body.value);

console.log(JSON.stringify(multiCheckBoxType.body));


If multiCheckBoxType is Promise object, it should be 


console.log(multiCheckBoxType.data.value);

console.log(JSON.stringify(multiCheckBoxType.data));








Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us