Respective checkbox to be selected on initial rendering of the grid

Hi team,


As I am working in syncfusion data grid, there i want respective checkbox to be selected on initial Rendering on the dataGrid as shown in the screenshot(checkbox.png) below


and please find a video recorded that I am facing an issue (checkbox.mp4)


I am using the property selectedRowIndex and initialize to 0.


Please help me on this issue
Here is the code

<template>

  <div class="loadout m-4">

    <b-modal :modal-class="[{ picklistModal: true }]" hide-header-close hide-footer ref="picklistModal">

      <div class="modal-header align-items-center m-4">

        <h6 class="modal-title mr-3" id="">

          <span class="badge badge-pill badge-secondary mr-2">{{ documentCount }}</span

          >Documents

        </h6>

        <div class="wrapper-filter pr-2">

          <ejs-daterangepicker

            :startDate="startDate"

            :endDate="endDate"

            :placeholder="waterMark"

          ></ejs-daterangepicker>

        </div>

        <div class="form-check mr-3">

          <input type="checkbox" class="form-check-input" id="exampleCheck1" />

          <label class="form-check-label" for="exampleCheck1">Schd date</label>

        </div>

        <div class="options">

          <div class="input-group-sm mr-3 d-flex">

            <label class="form-check-label pr-2 pt-1">Route</label>

            <multiselect

              select-Label=""

              selected-Label=""

              deselect-Label=""

              v-model="value"

              :options="options"

              :limit="2"

              :multiple="true"

              track-by="RouteDescription"

              :custom-label="customLabel"

              :close-on-select="false"

              :hide-selected="true"

            >

              <template slot="selection" slot-scope="{ values, isOpen }"

                ><span class="multiselect__single" v-if="values.length && !isOpen"

                  >{{ value.length }} selected</span

                ></template

              >

            </multiselect>

          </div>

        </div>

        <div class="col-2">

          <button type="button" class="btn btn-primary btn-sm" @click="filterWithRouteOptions">Submit</button>

        </div>

        <div class="float-right">

          <button class="ck-btn-txt right" data-dismiss="modal" aria-label="Close" @click="closeModal()">Cancel</button>

          <button class="ck-btn blue-btn right" data-dismiss="modal" aria-label="Close" @click="saveLoadDocument()">

            Save

          </button>

        </div>

      </div>

      <div class="m-2">

        <ejs-grid

          ref="loadoutmodal_Grid"

          :dataSource="dataGrid"

          :allowResizing="true"

          :allowFiltering="columnfilter"

          :dataBound="createdGrid"

          :allowSorting="true"

          :allowReordering="true"

          :showColumnChooser="true"

          :allowTextWrap="true"

          :rowSelected="rowSelected"

          :selectedRowIndex="selectedRowIndex"

          :selectionSettings='selectionOptions'

          :queryCellInfo="queryCellInfoEvent"

          :filterSettings="filterOptions"

          @actionBegin="gridActionBegin($event)"

        >

          <e-columns>

            <e-column type="checkbox" width="50"></e-column>

            <e-column

              field="DocumentNumber"

              :headerText="$t('deliveryorders.DocNo')"

              textAlign="left"

              width="100"

              maxWidth="120"

              :filter="filterOptions"

            ></e-column>

            <e-column

              field="Doctype"

              :headerText="$t('picklist.picklistdoctype')"

              textAlign="left"

              width="100"

              maxWidth="120"

              :filter="filterOptions"

            ></e-column>

            <e-column

              field="DocumentDate"

              :headerText="$t('picklist.DocDate')"

              textAlign="left"

              width="130"

              maxWidth="180"

              :template="formatDocumentDate"

              :filter="filterOptions"

            ></e-column>

            <e-column

              field="CustomerName"

              :headerText="$t('common.outlet')"

              textAlign="left"

              width="130"

              maxWidth="180"

              :filter="filterOptions"

            ></e-column>

            <e-column

              field="RouteName"

              :headerText="$t('picklist.deliveryroute')"

              textAlign="left"

              width="100"

              maxWidth="180"

              :filter="filterOptions"

            ></e-column>

            <e-column

              field="SalesmanName"

              :headerText="$t('common.salesman')"

              textAlign="left"

              width="100"

              maxWidth="180"

              :filter="filterOptions"

            ></e-column>

            <e-column

              field="TotalLines"

              :headerText="$t('common.lines')"

              textAlign="left"

              width="120"

              maxWidth="150"

              :filter="filterOptions"

            ></e-column>

            <e-column

              field="DocumentAmount"

              :headerText="$t('common.amount')"

              textAlign="left"

              width="90"

              minWidth="120"

              maxWidth="150"

              :filter="filterOptions"

            ></e-column>

          </e-columns>

        </ejs-grid>

        <b-pagination

          v-model="pagingDetails.currentPage"

          :total-rows="pagingDetails.rows"

          :per-page="pagingDetails.perPage"

          @change="onPageChange"

          aria-controls="deliveryNoteGridPagination"

          align="center"

        ></b-pagination>

      </div>

    </b-modal>

  </div>

</template>



<script>

import Vue from 'vue'

import api from '../../service'

import { mapActions } from 'vuex'

import { mapGetters } from 'vuex'

import { START_DATE } from '@/store/actions/user'

import { END_DATE } from '@/store/actions/user'

import Multiselect from 'vue-multiselect'

Vue.component('multiselect', Multiselect)

Vue.prototype.$eventHub = new Vue()



import {

  GridPlugin,

  Edit,

  DetailRow,

  Sort,

  ColumnChooser,

  Page,

  Resize,

  Filter,

  Reorder,

  CommandColumn,

} from '@syncfusion/ej2-vue-grids'

import { DropDownListPlugin } from '@syncfusion/ej2-vue-dropdowns'

import moment from 'moment'

Vue.use(GridPlugin)

Vue.use(DropDownListPlugin)

export default {

  name: 'load-out-modal',

  data() {

    return {

      startDate: moment().startOf('month').format('YYYY-MM-DD'),

      endDate: new Date().toISOString().split('T')[0],

      value: [],

      options: [],

      waterMark: 'Select a Date Range',

      formatStartDate: '',

      formatEndDate: '',

      dataGrid: [],

      loadoutmodal_Grid_Loaded: false,

      selectionOptions: { type: 'Mutliple', mode: 'Row' },

      selectedRowIndex: 0,

      documentCount: 0,

      // emptyRecords: true,

      picklistdocument: {},

      filterOptions: {

        ignoreAccent: true,

        mode: 'Immediate',

        operator: 'contains'

      },

      columnfilter: true,

      pagingDetails: {

        perPage: 0,

        rows: 0,

        currentPage: 1,

        records: 0

      },

      editSettings: {

        allowEditing: true,

        allowAdding: true,

        newRowPosition: 'Bottom'

      },

      showLoader: false,

      pickListReqBody: {

        _search: false,

        nd: new Date().getTime(),

        rows: 10,

        page: 1,

        sidx: 'DocumentNumber',

        sord: 'desc',

        _: new Date().getTime(),

        FromPickList: true,

        RouteFilter: '',

        IsDisableWarehouseCheck: 0,

        OutletRegistrationtype: ''

      },

      loadOutForm: {

        PickHeader: [],

        PickDetails: [],

        RoundOffOptions:"4",

        NetOffLimitValue:"1",

        DecimalPlacesRule:2,

      },

      PickHeader: {

        RouteType: null,

        InternalDocumentNo: 0,

        DocumentNumber: '',

        DocumentDate: moment().format('DD MMMM YYYY'),

        PickListDescription: '',

        RouteNumber: null,

        WarehouseID: null,

        VEHICLEID: null,

        DocumentStatus: 0,

        IsVanCapErrorWarned: 0,

        IsDisableWarehouseCheck: 0,

        selDNIDs: '',

        LastUpdateID: null,

      },

      formatDocumentDate: function () {

        return {

          template: Vue.component('columnTemplate', {

            template: `<p class="m-0 pt-1">

                <span>{{formatDate(data.DocumentDate)}}</span>

              </p> `,

            methods: {

              formatDate(data) {

                return moment(data).format('DD MMM YYYY')

              }

            }

          })

        }

      },

      selectedIndexesArray: []

    }

  },

  computed: {

    ...mapGetters(['getStartDate', 'getEndDate', 'getRefreshValue'])

  },

  props: ['formMode','currentIndex'],

  watch: {

    // update views(recall api calls) on date change

    // getStartDate() {

    // this.getPickListDocuments()

    // },

    // getEndDate() {

    // this.getPickListDocuments()

    // }

  },

  mounted() {

    this.pagingDetails.currentPage = 1

  },

  methods: {

    ...mapActions([START_DATE, END_DATE]),

    // startdateChanged() {

    // this.formatStartDate = moment(this.startDate).format('DD MMM YYYY')

    // this.$store.commit('START_DATE', this.formatStartDate)

    // },

    // defaultStartDate() {

    // if (localStorage.getItem('startdate') != null) {

    // return (this.startDate = localStorage.getItem('startdate'))

    // } else {

    // return (this.startDate = moment().startOf('month').format('YYYY-MM-DD'))

    // }

    // },

    // defaultEndDate() {

    // if (localStorage.getItem('enddate') != null) {

    // return (this.endDate = localStorage.getItem('enddate'))

    // } else {

    // return (this.endDate = new Date().toISOString().split('T')[0])

    // }

    // },

    // enddateChanged() {

    // this.formatEndDate = moment(this.endDate).format('DD MMM YYYY')

    // this.$store.commit('END_DATE', this.formatEndDate)

    // },

    createdGrid: function () {

      let headerFilterEle = this.$refs.loadoutmodal_Grid.ej2Instances

        .getHeaderTable()

        .querySelectorAll('.e-filterbarcell div')



      for (let i = 0; i < headerFilterEle.length; i++) {

          if (i == 0) {

            headerFilterEle[i].style.display = 'block'

          } else {

            headerFilterEle[i].style.display = 'none'

          }

      }

    },

    rowSelected: function (args) {

      this.selectedIndexesArray.push(args.data)

      console.log('rowSelected =>', this.selectedIndexesArray)

    },

    queryCellInfoEvent: function (args) {

      // Adds title to all columns/cells

      args.cell.title = args.data[args.column.field]

    },

    // ApplyFilter(args) {

    // this.startDate = args.startDate

    // this.endDate = args.endDate

    // this.startdateChanged()

    // this.enddateChanged()

    // },

    saveLoadDocument(status = 0) {

      let selIds = []

      this.selectedIndexesArray.map((item)=>{

          selIds.push(item.InternalDocumentNo)

      })

      this.PickHeader.RouteType = this.picklistdocument.RouteType ? this.picklistdocument.RouteType : null

      this.PickHeader.InternalDocumentNo = 0

      this.PickHeader.DocumentNumber = ""

      this.PickHeader.DocumentDate = moment().format('DD MMM YYYY')

      this.PickHeader.PickListDescription = ""

      this.PickHeader.RouteNumber = this.picklistdocument.RouteNumber ? this.picklistdocument.RouteNumber : null

      this.PickHeader.WarehouseID = this.picklistdocument.WarehouseID ? this.picklistdocument.WarehouseID :null

      this.PickHeader.VEHICLEID = this.picklistdocument.VehicleID ? this.picklistdocument.VehicleID: null

      this.PickHeader.DocumentStatus = 0

      this.PickHeader.IsVanCapErrorWarned = 0

      this.PickHeader.IsDisableWarehouseCheck = "0"

      this.PickHeader.selDNIDs = selIds.toString()

      this.PickHeader.LastUpdateID = ""

      this.loadOutForm.PickHeader[0] = JSON.parse(JSON.stringify(this.PickHeader))

      console.log('load out call', this.loadOutForm)

      this.showLoader = true

          const client = api()

          client

            .post('picklist', JSON.stringify(this.loadOutForm))

            .then(response => {

              console.log('load full',response.data)

              if (response.data.IntDocNo) {

                let toastMessage = 'Record created successfully!'

                this.$bvToast.toast(toastMessage, {

                  title: `Success`,

                  variant: 'success',

                  solid: true,

                  autoHideDelay: 3000

                })

                this.showLoader = false

                this.$refs.picklistModal.hide()

                this.updateCurrentTab(response.data, status)

              } else if (response.data.LastUpdateID == '') {

                let toastMessage = response.data.error

                this.$bvToast.toast(toastMessage, {

                  title: `Warning`,

                  variant: 'warning',

                  solid: true,

                  autoHideDelay: 3000

                })

              } else {

                this.$bvToast.toast('Unable to create a load document', {

                  title: `Warning`,

                  variant: 'warning',

                  solid: true,

                  autoHideDelay: 3000

                })

              }

            })

        .catch(() => {

          console.log('Unable to create/update stock transfer!')

        })

    },

    updateCurrentTab(data, updatedDocStatus) {

      // update saleOrderDetail and update tab

      let loadOutDetail = {}

      loadOutDetail.DocumentStatus = updatedDocStatus

      loadOutDetail.LastUpdateID = data.LastUpdateID

      loadOutDetail.DocumentNumber = data.DocumentNumber

      loadOutDetail.InternalDocumentNo = data.IntDocNo

      loadOutDetail.WarehouseID = this.picklistdocument.WarehouseID

      loadOutDetail.DeliveryRoute = this.picklistdocument.DeliveryRoute

      loadOutDetail.Warehouse = this.picklistdocument.Warehouse

      loadOutDetail.vehicleTitle = this.picklistdocument.VehicleTitleWithCode

      loadOutDetail.RouteType = this.picklistdocument.RouteType

      loadOutDetail.CapacityCS = this.picklistdocument.CapacityCS

      loadOutDetail.VehicleTitleAndCode = this.picklistdocument.VehicleTitleWithCode

      loadOutDetail.CapacityWeight = this.picklistdocument.CapacityWeight

      loadOutDetail.BasePickQuantity = this.rowUpdatedData.BasePickQuantity

      loadOutDetail.updateCurrentTab = true

      loadOutDetail.lastTabIndex = 5

      this.$emit('gotoEditTab', loadOutDetail)

    },

    // changeFormat(args) {

    // this.ApplyFilter(args)

    // localStorage.setItem('startdate', args.startDate)

    // localStorage.setItem('enddate', args.endDate)

    // },

    fetchPicklists(e, routeDetails,selectedarray) {

      console.log('documents content', e, routeDetails,selectedarray)

      // this.selectedDNs = selectedarray

      this.options = routeDetails

      this.picklistdocument = e

      this.dataGrid = []

      setTimeout(() => {

        this.getPickListDocuments()

        this.$refs.picklistModal.show()

      },100)

    },

    closeModal() {

      // this.emptyRecords = true

      this.$emit('gotoAddTab')

      if(this.formMode == 'edit'){

        this.$emit('editModeTab',this.currentIndex)

      }

      this.$refs.picklistModal.hide()

    },

    customLabel(option) {

      return `${option.RouteDescription}`

    },

    filterWithRouteOptions() {

      let routeNumbers = []

      this.value.map(item => {

        if (item.RouteNumber) {

          routeNumbers.push(item.RouteNumber)

        }

      })

      const client = api()

      client

        .get('/picklist', {

          params: {

            _search: false,

            nd: new Date().getTime(),

            rows: 100,

            page: 1,

            sidx: 'DocumentNumber',

            sord: 'desc',

            _: new Date().getTime(),

            FromPickList: true,

            PickListID: 0,

            RouteNumber: this.picklistdocument.RouteNumber,

            WarehouseID: this.picklistdocument.WarehouseID,

            RouteFilter: routeNumbers.toString(),

            IsDisableWarehouseCheck: 0,

            FromDate: this.getStartDate,

            ToDate: this.getEndDate

          }

        })

        .then(response => {

          this.dataGrid = response.data.ResultedList ? response.data.ResultedList : []

        })

        .catch(error => {

          console.error(error, 'Unable to find warehouseNames')

        })

    },

    gridActionBegin(event) {

      // console.log(event, 'paging console')

      if (event.requestType === 'paging') {

        // this.onPageChange(event)

      }

      if (event.requestType === 'sorting') {

        this.onSortChange(event)

      }

      if (event.requestType === 'filtering') {

        // if (event.action === 'clearFilter') {

        // this.onColumnFilter(event)

        // } else {

        this.onColumnFilter(event)

        // }

      }

    },

    onSortChange(params) {

      console.log(params)

      this.pickListReqBody.sidx = params.columnName

      this.pickListReqBody.sord = params.direction === 'Ascending' ? 'asc' : 'desc'

      this.pickListReqBody.page = 1

      this.getPickListDocuments()

    },

    onColumnFilter(params) {

      if (

        params.currentFilterObject.field !== '' &&

        params.currentFilterObject.value !== '' &&

        params.action !== 'clearFilter'

      ) {

        this.pickListReqBody._search = true

        this.pickListReqBody[params.currentFilterObject.field] = params.currentFilterObject.value

      } else {

        this.pickListReqBody._search = false

        delete this.pickListReqBody[params.currentFilterObject.field]

      }

      this.pickListReqBody.page = 1

      this.getPickListDocuments()

    },

    onPageChange(event) {

      this.pagingDetails.currentPage = event

      this.pickListReqBody.page = +this.pagingDetails.currentPage

      this.getPickListDocuments()

    },

    getPickListDocuments() {

      const client = api()

      this.pickListReqBody.RouteNumber = this.picklistdocument.RouteNumber

      this.pickListReqBody.WarehouseID = this.picklistdocument.WarehouseID

      this.pickListReqBody.PickListID = this.picklistdocument.InternalDocumentNo ? this.picklistdocument.InternalDocumentNo: 0,

      this.pickListReqBody.FromDate = this.startDate,

      this.pickListReqBody.ToDate = this.getEndDate,

      client

        .get('/picklist', {

          params: this.pickListReqBody

        })

        .then(response => {

          this.documentCount = response.data.records

          this.dataGrid = response.data.ResultedList ? response.data.ResultedList : []

          this.pagingDetails.currentPage = response.data.page ? +response.data.page : 1

          this.pagingDetails.rows = response.data.records

          this.pagingDetails.perPage = 10

        })

        .catch(error => {

          console.error(error, 'Unable to find warehouseNames')

        })

    }

  },



  provide: {

    grid: [DetailRow, Filter, Edit, Sort, ColumnChooser, Page, Resize, Reorder, CommandColumn]

  }

}

</script>




        

Regards,
Cyril Ovely



Attachment: checkbox_46413714.zip

2 Replies

NS Nithya Sivaprakasam Syncfusion Team June 17, 2022 05:02 PM UTC

Hi Cyril,


Currently, we are checking your query and we will update further details on or before June 21, 2022.


Until then, we appreciate your patience.


Regards,

Nithya S.



NS Nithya Sivaprakasam Syncfusion Team June 21, 2022 05:39 PM UTC

Hi Cyril,


Thanks for your patience.


By analyzing your video demo we found that the Grid gets refreshed after the initial render. So it clears the selected records from the Grid. By default, the Grid will clear the selection when it is refreshed.


Kindly ensure the below cases to avoid this,


  1. Are you changing the Grid properties or variables during the Grid render? (Which refreshes the Grid)
  2. If yes, comment on that code and check the issue once again.
  3. If you want to maintain the selection for all the Grid actions like Paging, Filtering, Refresh, etc., you can use the persistSelection feature.


 

<template>

    <ejs-grid

      ref="loadoutmodal_Grid"

      :dataSource="dataGrid"

      :selectionSettings="selectionOptions"

    >

      <e-columns>

        <e-column type="checkbox" width="50"></e-column>

        <e-column

          field="DocumentNumber"

          headerText="deliveryordersDocNo"

          textAlign="left"

          width="100"

          isPrimaryKey="true"

          maxWidth="120"

          :filter="filterOptions"

        ></e-column>

       ---

      </e-columns>

    </ejs-grid>

</template>

 

<script>

---

 

export default {

  name: "load-out-modal",

 

  data() {

    return {

      selectionOptions: {

        persistSelection: true,

        type: "Mutliple",

        mode: "Row",

      },

      selectedRowIndex: 0,

    };

  },

  },

};

</script>

 


Note:


If ‘persistSelection’ set to true, then the Grid selection is persisted on all the operations. For persisting selection in the Grid, any one of the columns should be enabled as a primary key. The primaryKey field should contain unique values in the dataSource.


https://ej2.syncfusion.com/vue/documentation/grid/selection/check-box-selection/


Please get back to us if you need further assistance.


Regards,

Nithya Sivaprakasam.


Loader.
Up arrow icon