How to create an Employee using x++ code.

In this blog we will show you how to create an employee by using code x++

 1

We will use the code below, please notice that this is a compilation of various methods of a class.

 X++ |  copy code |? 
001
//EMilio Iza
002
//2014-06-13
003
//EI_LoadHCMWorker: Declaración de variables
004
class EI_GELoadHCMWorker Extends Runbase
005
{
006
    DialogRunbase                               dialog;
007
//variables globales
008
    DialogField                 dlgfiledata;
009
    DialogField                 dlgfiledata2;
010
    FileNameOpen                filedata;
011
    FileNameOpen                fileErrors;
012
    TransactionLog              transactionLog;
013
    asciiIo                     trans;
014
    asciiIo                     error;
015
    str                         errorTxt;
016
    container                   transLine;
017
    container                   errors;
018
    boolean                     exist;
019
    str                         Lineread;
020
    str                         Line;
021
    boolean                     errorfileopen;
022
    AsciiIo                     fileError;
023
    FileNameOpen                filedataError;
024
    DialogField                 dlgrecordnumber;
025
    Counter                     countLine;
026
    DirPartyContactInfoView     contactInfo;
027
 
028
 
029
 
030
    #DEFINE.CurrentVersion(1)
031
    #localmacro.CurrentList
032
        filedata,
033
        filedataError
034
    #endmacro
035
 
036
}
037
 
038
 
039
 
040
//EMilio Iza
041
//2014-06-13
042
//EI_LoadHCMWorker: Método pricipal
043
static void main(Args _args)
044
{
045
    EI_GELoadHCMWorker     GELoadHCMWorker;
046
    ;
047
 
048
    GELoadHCMWorker = new EI_GELoadHCMWorker();
049
 
050
    if(GELoadHCMWorker.prompt())
051
        GELoadHCMWorker.run();
052
}
053
 
054
 
055
public Object dialog()
056
{
057
    Object ret;
058
    ;
059
 
060
 
061
    dialog = super();
062
 
063
    dlgfiledata     = dialog.addField(extendedTypeStr(FileNameOpen), 'Fichero de carga de datos',filedata);
064
    dlgfiledata2    = dialog.addField(extendedTypeStr(FilePath),'Fichero de errores',filedataError);
065
    dlgrecordnumber = dialog.addField(extendedTypeStr(Counter),'Número de Registros a Importar');
066
 
067
 
068
    return dialog;
069
}
070
 
071
 
072
 
073
 
074
 
075
 
076
public boolean getFromDialog()
077
{
078
    boolean ret;
079
    ;
080
 
081
    ret = super();
082
 
083
    filedata        = dlgfiledata.value();
084
 
085
    filedataError   = dlgfiledata2.value();
086
 
087
    return ret;
088
}
089
 
090
 
091
 
092
//EMilio Iza
093
//2014-06-13
094
//EI_LoadHCMWorker:
095
public void run()
096
{
097
    HcmWorker               HcmWorker;
098
    dirPerson               dirPerson;
099
    dirPersonName           dirPersonName;
100
    HcmWorkerTitle          HcmWorkerTitle;
101
    HcmPersonPrivateDetails HcmPersonPrivateDetails;
102
    HcmPersonDetails        HcmPersonDetails;
103
    HcmEmployment           HcmEmployment;
104
    HcmTitle                HcmTitle;
105
    DimensionValue          dim1,dim2,dim3,dim4,dim5,dim6,dim7,dim8,dim9;
106
    HcmPersonnelNumberId    PersonnelNumber;
107
    Name                    firstName, middleName, lastName, name, secondLastName;
108
    dirPartyTable           dirPartyTable;
109
    date                    d;
110
 
111
    DirPartyLocation            DirPartyLocation;
112
    LogisticsLocation           LogisticsLocation, LogisticsLocationElectronic;
113
    LogisticsElectronicAddress  LogisticsElectronicAddress;
114
 
115
    str strEmail;
116
    str strInternet;
117
    str strPhone;
118
    str strTelex;
119
    str strExt;
120
    HcmTitleRecId vTitle;
121
    str          vProfessionalTitle;
122
 
123
    int i;
124
    int j;
125
    str                         vTipoDocumento;
126
    HcmEmploymentSeniorityDateTime vFechaAntiguedad;
127
    int percentage=0;
128
     SysOperationProgress progressbar = new SysOperationProgress();
129
 
130
    Array _recIds;
131
    ;
132
 
133
    try
134
    {
135
 
136
        if (!fileData)
137
            throw error ("@SYS18678",fileData);
138
 
139
        super();
140
        info(strFmt("inicio %1", time2str(timeNow(),1,1)));
141
 
142
        trans           = new AsciiIo(filedata,"R");
143
        trans.inFieldDelimiter(";");
144
        Transline       = trans.read();        progressbar.setCaption("Proveedores Importados");
145
        progressbar.setAnimation(#AviUpdate);
146
        progressbar.setTotal(countLine);
147
 
148
 
149
        while (trans.status() == IO_Status::Ok)
150
        {
151
            percentage++;
152
            progressbar.setText(strfmt("Registro %1", percentage));
153
            progressbar.setCount(percentage, 1);
154
 
155
            PersonnelNumber = strLRTrim(conpeek(transline,1));
156
            PersonnelNumber = strltrim(PersonnelNumber);
157
 
158
            ttsBegin;
159
            HcmWorker = hcmWorker::findByPersonnelNumber(PersonnelNumber,true); 
160
            if(!HcmWorker)
161
                hcmWorker.PersonnelNumber = PersonnelNumber;
162
 
163
           firstName = strLRTrim(conpeek(transline,2));                 
164
            lastName  = strLRTrim(conpeek(transline,3));              
165
            name  = firstName + " " + lastName;
166
 
167
 
168
            if (HcmWorker.Person)
169
            {
170
                dirPartyTable = dirPartyTable::find(dirPerson::find(HcmWorker.Person).PartyNumber);
171
                if (!dirPartyTable)
172
                {
173
                    DirPartyTable = DirPartyTable::GIcreateNew(DirPartyType::Person, name, "", firstName, middleName, lastName, PersonnelNumber, '', '', secondLastName);
174
                }
175
                else
176
                {
177
                    dirPersonName   = DirPersonName::find(HcmWorker.Person, true);
178
                    dirPersonName.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
179
                    dirPersonName.FirstName     = firstName;
180
                    dirPersonName.LastName      = lastName;
181
                    dirPersonName.write();
182
                }
183
            }
184
            else
185
            {
186
                DirPartyTable = DirPartyTable::GIcreateNew(DirPartyType::Person, name, "", firstName, middleName, lastName, PersonnelNumber, '', '', secondLastName);
187
            }
188
 
189
            dirPerson = dirPerson::find(DirPartyTable.RecId, true);
190
 
191
            dirPerson.ProfessionalTitle = conPeek(this.getValue(strLRTrim(conpeek(transline,5))), 2); 
192
            vProfessionalTitle  = dirPerson.ProfessionalTitle;
193
            dirPerson.Gender            = str2num(conpeek(transline,7));
194
            dirPerson.NameSequence      = DirNameSequence::find("FirstLast").RecId;
195
            dirPerson.LanguageId        = "ES";
196
 
197
            dirPerson.write();
198
 
199
            HcmWorker.Person = dirPerson.RecId;
200
 
201
            HcmWorker.write(); 
202
 
203
 
204
 
205
            if(!HcmTitle::findByTitle(dirPerson.ProfessionalTitle))
206
            {
207
                HcmTitle.TitleId    = dirPerson.ProfessionalTitle;
208
                HcmTitle.insert();
209
            }
210
 
211
            HcmEmployment = HcmEmployment::findByWorkerLegalEntity(HcmWorker.RecId, CompanyInfo::find().RecId, DateTimeUtil::minValue(), DateTimeUtil::maxValue(), true);
212
 
213
 
214
            if(!HcmEmployment)
215
            {
216
                HcmEmployment.LegalEntity    = CompanyInfo::find().RecId; //"SEG"
217
                HcmEmployment.Worker         = HcmWorker.RecId;
218
                if (conpeek(transline,13) != "")
219
                {
220
                    d = str2date(conpeek(transline,13),321);    //EI_LoadHCMWorker.ln
221
                    HcmEmployment.ValidFrom = DateTimeUtil::newDateTime(d, 0);
222
                }
223
                else
224
                    HcmEmployment.ValidFrom      = DateTimeUtil::minValue();
225
 
226
                if (conpeek(transline,14) != "")
227
                {
228
                    d = str2date(conpeek(transline,14),321);    //EI_LoadHCMWorker.ln
229
                    HcmEmployment.ValidTo        = DateTimeUtil::newDateTime(d, 0);
230
                }
231
                else
232
                    HcmEmployment.ValidTo        = DateTimeUtil::maxValue();
233
 
234
            }
235
            dim1 = conPeek(this.getValue(strLRTrim(conpeek(transline,16))),1);
236
            dim2 = conPeek(this.getValue(strLRTrim(conpeek(transline,18))),1);
237
            dim3 = conPeek(this.getValue(strLRTrim(conpeek(transline,17))),1);
238
            dim4 = "";
239
            dim5 = "";
240
            dim6 = "";
241
            dim7 = "";
242
            dim8 = conPeek(this.getValue(strLRTrim(conpeek(transline,21))),1);
243
            dim9 = "";
244
 
245
 
246
            HcmEmployment.EmploymentType = str2num(conpeek(transline,19));
247
 
248
            HcmEmployment.DefaultDimension = this.setDefaultLedgerDimension('',
249
                                                                                           dim1,  // Centro de Costos
250
                                                                                           dim2,  // Linea de Negocio
251
                                                                                           '',//dim3,  // Local
252
                                                                                           '',
253
                                                                                           '',
254
                                                                                           dim8);
255
 
256
            if(!HcmEmployment)
257
                HcmEmployment.write();
258
            else
259
                HcmWorkerTransition::newUpdateHcmEmployment(hcmEmployment, HcmEmployment.ValidFrom, HcmEmployment.ValidTo); //EI_LoadHCMWorker.ln
260
 
261
            /////////////////////////////////////////////////////////////////////////////
262
            vTitle = HcmTitle::findByTitle(vProfessionalTitle).RecId;
263
 
264
            //HcmWorkerTitle.clear();
265
            HcmWorkerTitle = HcmWorkerTitle::findByWorker(HcmWorker.RecId, DateTimeUtil::minValue(), DateTimeUtil::maxValue(), true);
266
 
267
            if(!HcmWorkerTitle)
268
            {
269
                    HcmWorkerTitle.Worker = HcmWorker.RecId;
270
            }
271
 
272
            if (conpeek(transline,4) != "")
273
            {
274
                d = str2date(conpeek(transline,4),321);   //EI_LoadHCMWorker.ln
275
                HcmWorkerTitle.SeniorityDate = DateTimeUtil::newDateTime(d, 0, DateTimeUtil::getCompanyTimeZone());
276
                vFechaAntiguedad = HcmWorkerTitle.SeniorityDate;
277
            }
278
            else
279
            {
280
                HcmWorkerTitle.SeniorityDate = DateTimeUtil::minValue();
281
                vFechaAntiguedad = HcmWorkerTitle.SeniorityDate;
282
            }
283
 
284
            HcmWorkerTitle.Title = vTitle;
285
            //HcmWorkerTitle.insert();
286
            HcmWorkerTitle.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
287
            HcmWorkerTitle.SeniorityDate = vFechaAntiguedad;
288
            HcmWorkerTitle.ValidFrom = DateTimeUtil::minValue();
289
            HcmWorkerTitle.ValidTo = DateTimeUtil::maxValue();
290
            //HcmWorkerTitle.update();
291
            HcmWorkerTitle.write();
292
            /////////////////////////////////////////////////////////////////////////////////////
293
 
294
            HcmPersonPrivateDetails = HcmPersonPrivateDetails::findByPerson(dirPerson.RecId,true);
295
            //if(!HcmPersonPrivateDetails)
296
            //{
297
                //HcmPersonPrivateDetails.clear();
298
                HcmPersonPrivateDetails.Person = dirPerson.RecId;
299
                //HcmPersonPrivateDetails.BirthDate = str2date(conpeek(transline,6),123);  //EI_LoadHCMWorker.old
300
                HcmPersonPrivateDetails.BirthDate = str2date(conpeek(transline,6),321);    //EI_LoadHCMWorker.ln
301
                HcmPersonPrivateDetails.Gender    = str2num(conpeek(transline,7));
302
                //HcmPersonPrivateDetails.insert();
303
                HcmPersonPrivateDetails.write();
304
            //}
305
 
306
 
307
            vTipoDocumento = strLRTrim(conpeek(transline,26));
308
 
309
            HcmPersonDetails = HcmPersonDetails::findByPerson(dirPerson.RecId);
310
            HcmPersonDetails.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
311
            HcmPersonDetails.selectForUpdate(true);
312
            //if(!HcmPersonDetails)
313
            //{
314
                //HcmPersonDetails.clear();
315
                HcmPersonDetails.Person            = dirPerson.RecId;
316
                HcmPersonDetails.MaritalStatus     = str2num(conpeek(transline,15));
317
                //HcmPersonDetails.MaritalStatus     = str2num(conPeek(this.getValue(conpeek(transline,15)),1));
318
                HcmPersonDetails.ValidTo           = DateTimeUtil::maxValue();
319
                HcmPersonDetails.LATPEIDDocumentTypes = LATPEIDDocumentTypes::findDocumentType(vTipoDocumento).RecId; // Tipo de Documento de Identidad
320
                //HcmPersonDetails.insert();
321
                HcmPersonDetails.write();
322
            //}
323
 
324
            strInternet = strLRTrim(conpeek(transline,8));
325
            strEmail    = strLRTrim(conpeek(transline,9));
326
            strPhone    = strLRTrim(conpeek(transline,12));
327
            strTelex    = strLRTrim(conpeek(transline,10));
328
            strExt      = strLRTrim(conpeek(transline,11));
329
 
330
            // LogisticsLocationElectronic
331
            if (strInternet)
332
            {
333
 
334
                LogisticsLocationElectronic = LogisticsLocation::create("Dirección internet", NoYes::yes);
335
                LogisticsElectronicAddress.clear();
336
                LogisticsElectronicAddress.Location = LogisticsLocationElectronic.RecId;
337
                LogisticsElectronicAddress.Description = "Dirección internet";
338
                LogisticsElectronicAddress.Type     = LogisticsElectronicAddressMethodType::URL;
339
                LogisticsElectronicAddress.Locator  = strInternet;
340
                LogisticsElectronicAddress.insert();
341
                //DirParty::addLocation(dirPerson.RecId, LogisticsLocationElectronic.RecId);
342
                _recIds = new Array(Types::Int64);
343
                _recIds.value(1,LogisticsLocationElectronic.RecId);
344
                //_recIds[1] = LogisticsLocationElectronic.RecId;
345
                HcmWorker.addLocations(_recIds,NoYes::Yes);
346
            }
347
            if (strEmail)
348
            {
349
                LogisticsLocationElectronic = LogisticsLocation::create("Correo electrónico", NoYes::No);
350
                LogisticsElectronicAddress.clear();
351
                LogisticsElectronicAddress.Location = LogisticsLocationElectronic.RecId;
352
                LogisticsElectronicAddress.Description = "Correo electrónico";
353
                LogisticsElectronicAddress.Type     = LogisticsElectronicAddressMethodType::Email;
354
                LogisticsElectronicAddress.Locator  = strEmail;
355
                LogisticsElectronicAddress.insert();
356
 
357
                DirParty::addLocation(dirPerson.RecId, LogisticsLocationElectronic.RecId);
358
 
359
                DirPartyTable = DirPartyTable::find(DirPartyTable.PartyNumber, true);
360
                DirPartyTable.PrimaryContactEmail = LogisticsElectronicAddress.RecId;
361
                DirPartyTable.doUpdate();
362
                            }
363
            if (strTelex)
364
            {
365
                LogisticsLocationElectronic = LogisticsLocation::create("Teléfono móvil", NoYes::No);
366
                LogisticsElectronicAddress.clear();
367
                LogisticsElectronicAddress.Location = LogisticsLocationElectronic.RecId;
368
                LogisticsElectronicAddress.Description = "Teléfono móvil";
369
                LogisticsElectronicAddress.Type     = LogisticsElectronicAddressMethodType::Phone;
370
                LogisticsElectronicAddress.Locator  = strTelex;
371
                LogisticsElectronicAddress.insert();
372
                DirParty::addLocation(dirPerson.RecId, LogisticsLocationElectronic.RecId, false, false);
373
 
374
 
375
            }
376
            if (strPhone)
377
            {
378
                LogisticsLocationElectronic = LogisticsLocation::create("Teléfono fijo", NoYes::No);
379
                LogisticsElectronicAddress.clear();
380
                LogisticsElectronicAddress.Location = LogisticsLocationElectronic.RecId;
381
                LogisticsElectronicAddress.Description = "Teléfono fijo";
382
                LogisticsElectronicAddress.Type     = LogisticsElectronicAddressMethodType::Phone;
383
                LogisticsElectronicAddress.Locator  = strPhone;
384
                LogisticsElectronicAddress.LocatorExtension = strExt;
385
                LogisticsElectronicAddress.insert();
386
                DirParty::addLocation(dirPerson.RecId, LogisticsLocationElectronic.RecId, false, true); // Primary
387
                                DirPartyTable = DirPartyTable::find(DirPartyTable.PartyNumber, true);
388
                DirPartyTable.PrimaryContactPhone = LogisticsElectronicAddress.RecId;
389
                DirPartyTable.doUpdate();
390
 
391
 
392
            }
393
            transLine    = trans.read();
394
            j = j + 1;
395
            //Debug::printDebug(j);
396
            ttsCommit;
397
 
398
        }
399
 
400
        info(strFmt("final %1", time2str(timeNow(),1,1)));
401
        if(errorTxt)
402
        {
403
            this.writeerror();
404
//            throw(Exception::Error);
405
        }
406
        else
407
        {
408
            info("Proceso finalizado");
409
        }
410
        //ttscommit;
411
    }
412
    catch (exception::Error)
413
    {
414
        error("Proceso cancelado");
415
        ttsabort;
416
    }
417
 
418
}
419

So when executing the class we got the following dialog.

2

We load the csv file:

 3

And finally, we can see the employee created in the image below:

4

With this you can load a batch of employees when migrating from another system or another version of Dynamics AX. Hope it helps, and please leave your thoughts on the comment section.

  • Cande Lujan

    Hello :
    How is the method DirPartyTable::GIcreateNew

    I will appreciate your help