vendredi 29 avril 2011

How to change the caption of a form according to the caller form

You can do that in the method active of your dataSource
public int active()
{
    boolean         canEdit = true;
    ;
    ret = super();

    element.design().caption(element.buildCaptionTextForActive());

    return ret;
}

Add this method to your form

str buildCaptionTextForActive()
{
    str activeLabel;
    ;

        // Build the string with details of the current category to use as label on the form caption
   if( ThyProjForcasTable.ProjCategoryType == ThyProjforecast::Hour)
   {
        activeLabel = strfmt("%1 - %2: %3, %5","@SYS53037","@SYS82923",ThyProjForcasTable.ProjForecastModelId,
                             "@SYS10223",ThyProjForcasTable.ProjId);
   }
   else if ( ThyProjForcasTable.ProjCategoryType == ThyProjforecast::Cost)
   {
        activeLabel = strfmt("%1 - %2: %3, %5","@SYS78785","@SYS82923",ThyProjForcasTable.ProjForecastModelId,
                             "@SYS10223",ThyProjForcasTable.ProjId);
   }
   else
   {
        activeLabel = strfmt("%1 - %2: %3, %5","@SYS119188","@SYS82923",ThyProjForcasTable.ProjForecastModelId,
                             "@SYS10223",ThyProjForcasTable.ProjId);
   }
   return activeLabel;
}

How to enable and disable editing fields in a grid according to records in a table

To do this override the method active from the dataSource of your grid

public int active()
{
    boolean         canEdit = true;
    ForecastModel   forecastModel;
    int             ret;
    ;

    ret = super();

   
    if (ThyProjForcasTable.ProjForecastModelId)
    {
        forecastModel = ForecastModel::find(HeadingSub::Heading, ThyProjForcasTable.ProjForecastModelId);

        if (forecastModel && forecastModel.Blocked)
            canEdit = false;
    }

    this.allowEdit(canEdit);
    this.allowDelete(canEdit);
    Generate_period.enabled(canEdit);


    return ret;
}

How to disable or enable calling an object ( report or form )

If you have to call a form or a report when from another form or class you can throw error in init method of your object( form or report) when trying to open it 

Here is an example :

     if (!element.args().caller())
    {
        throw error("@SYS22539");
    }

jeudi 28 avril 2011

How to write code for sorting field in a grid

Assuming you are trying to sort field CustGroup on datasource CustTable:

1) add ComboBox on form, set Name=ComboSortOrder, AutoDeclaration=Yes and EnumType=SortOrder

2) override modified() method on ComboBox form control to call executeQuery() of the datasource

public boolean modified()
{
   boolean ret;
   ;
   ret = super();

   CustTable_ds.executeQuery();

   return ret;
}

3) override executeQuery() method on datasource to change sortorder before actual fetch of records

public void executeQuery()
{;
    CustTable_ds.query().dataSourceNo(1).sortClear();
    CustTable_ds.query().dataSourceNo(1).addSortField(fieldNum(CustTable,
    CustGroup), ComboSortOrder.selection());
 
   // you can change that to  
    //CustTable_ds.query().dataSourceNo(1).addSortField(fieldNum(CustTable,
    //CustGroup), SortOrder::Ascending); 
    //If you want to display fields in an ascending order. 

    super();
}
 
Notice  
There is a sort method on each control, overriding which you can influence the actual actions
 which happed when you click on the header of a column

How to get records from a table in a specific order ascending or descending

The following code example demonstrates how the results from a select query can be ordered and grouped.

While select myTable 
      order by Field1 asc, Field2 desc
{
   //...
}

While select  myTable 
       group by Field1 desc
{
   // ...


See an example in custTable.lastPayment() 

CustTrans lastPayment()
{
    CustTrans   custTrans;

    select firstonly custTrans
        index hint AccountDateIdx
        order by TransDate desc, Voucher desc
        where custTrans.AccountNum  == this.AccountNum   &&
              custTrans.Invoice     == ''                &&
              custTrans.AmountCur   < 0;

    return custTrans;
}


You can also follow the example in  a report

boolean  fetch()
{
      QueryRun                tradeLoopTrans;
      tradeLoopTrans = new TradeLoopTrans(vendPurchOrderJour,        tablenum(VendPurchOrderTrans)).    buildQueryRun();
      vendFormletterDocument = VendFormletterDocument::find();
          
      tradeLoopTrans.query().dataSourceTable(
      tablenum(vendPurchOrderTrans)).addSortField(    fieldnum(vendPurchOrderTrans,bfpGroupId));
}

mercredi 27 avril 2011

How to force saving records from a grid when clicking in a button

To do so override the method cliked of the button and add : 
MyDataSource_ds.write();

void clicked()
{
    boolean             ret;
    Qty                 Qty;
    ;

 
    super();

    if (ThyProjForcasTable.ProjCategoryType == Thyprojforecast::hour)
    {
        element.CheckQty(ForcostEmplTab, ProjForecastEmpl_DS.QtyRemains(), ProjForecastEmpl_DS.EmplCostAmount());
    }
    if (ThyProjForcasTable.ProjCategoryType == Thyprojforecast::sales)
    {
        element.CheckQty(ForCastSales, ForecastSales_DS.QtyRemains(), ForecastSales_DS.SalesCostAmount());
    }
    if (ThyProjForcasTable.ProjCategoryType == Thyprojforecast::cost)
    {
        element.CheckQty(ForCastCost, ProjForecastCost_DS.QtyRemains(), ProjForecastCost_DS.CostAmount() );
    }

    ThyProjForcasTable_ds.write();


}

How to display an image according to test result OK or Not Ok using macro of AX

To do so you must use the macro : resAppl from the AOT and this following method:

/// <summary>
/// A display method that converts the test result to an image ID.
/// </summary>
/// <returns>
/// Image_Ok if the test passed; otherwise, Image_NotOk
/// </returns>

//BP Deviation Documented

display ProjTestImage displayResultImage()
{
    #resAppl
    ;

    //Check if user has security access
    if(!hasFieldAccess(tablenum(ThyProjForcasTable),
                       fieldnum(ThyProjForcasTable, NoYesId),
                       AccessType::View))
    {
        return -1;
    }

    if(this.NoYesId == Noyes::Yes)
        return #Image_Ok;

    return #Image_NotOk;
}


See example in the form InventQualityOrderTable in the AOT.

lundi 25 avril 2011

How to display an image from Resources in a grid of a form

Axapta provides a very handy feature to allow developers to ship their solution with Axapta built-in image files. In Application Object Tree, you can find resources node. Select resources node and right click; select Create from File, specify the file location for the new resource file. After that you can use this resource file in Axapta without specifying an absolute file path in your hard disk.
Then let’s see how to use this kind of files in Axapta.
First, pick up the resource node from AOT;
SysResource::getResourceNode();

Then generate a temporary file for this resource file;
SysResource::saveToTempFile()

Finally specify the temporary file path for controls.

Here comes an example to show how to use a resource file as a background image of  a given form.

If you don't want to indicate the path to display an imge in a grid you can use : Resources in the AOT 
and call your image as following :

public display FilePath ShowMyResource()
{
#AOT
ResourceNode resourceNode;
FilePath filePathLogo;
;

resourceNode = SysResource::getResourceNode('NameOfTheResource');

   if (resourceNode)
   {
       resourceNode.AOTload();
       filePathLogo =  SysResource::saveToTempFile(resourceNode);
   }


   return filePathLogo;
}
 
Otherwise, you can use this
  
display Bitmap bitmap()
{
    Bitmap bitmap;
    Bindata     binData = new BinData();

    if (binData.loadFile('c:\\1.bmp'))
    {
        bitmap = binData.getData();
    }
    return bitmap;
}  

jeudi 21 avril 2011

How to display image in each line of a grid

  1. Create ImageList in form.init():
    imageList = new ImageList(ImageList::smallIconWidth(), ImageList::smallIconHeight();
    Image image = new Image();
    ;
    image.loadImage(filename)
    imageList.add(image);
    // ...
    image.loadImage(filename-n)
    imageList.add(image);
    
    ImageList must be declared in ClassDEclaration section.
  2. Set AutoDaclaration property of Window field in the Grid to "Yes".
  3. Set ImageList for the window field in the method init() of form:
    MyWindow.imageList(imageList);
    
  4. On the Table which you are using on the form create the display method. Something like this:
    display int status()
    {
       if(this.amount > 10)
           return 5;  // 5th image from image list
       else
           return 6;
    }
    
    1. Set properties DataSource and DataMethod for your window control:
      DataSource = DataMethod = status

How to send alert to user using X++

// To send Alert to User From Code
void sendAlertToUsers()
{
SysMailer mail;
UserInfo UserInfo;
EventInbox inbox;
EventInboxId inboxId;
;

select UserInfo where UserInfo.id == CurUserId();
inboxId = EventInbox::nextEventId();

inbox.initValue();
inbox.ShowPopup = NoYes::Yes; // To show Pop up
inbox.Subject = "Aleart Message Through Code";
inbox.Message = "Testing Alerts";
inbox.AlertedFor = "This alert is just for information(Testing)";
inbox.SendEmail = false;
inbox.UserId = UserInfo.Id;
inbox.TypeId = classnum(EventType);
//Enter Table and Field Details
inbox.AlertTableId = TableNum(EmplTable); // Table for which Alert is Generated
inbox.AlertFieldId = fieldNum(Empltable ,Name); // Field for which Alert is Generated
inbox.TypeTrigger = EventTypeTrigger::FieldChanged;
inbox.CompanyId = CurExt();
inbox.InboxId = inboxId;
inbox.AlertCreatedDate = systemdateget();
inbox.AlertCreateTime = timeNow();
inbox.insert();
}

How to add an image by X++

Image image = new Image();
image.loadImage(_filePath);
image.getData();

How to send email using X++

SysMailer mailer = new SysMailer();
SysEmailParameters parameters = SysEmailParameters::find();
mailer.fromAddress('moulikaku@hotmail.com');
mailer.fromName('minnu@gmail.com');
mailer.subject('What are you doing tonite???');
if (parameters.DNSServerName)
{
mailer.DNSServers().add(parameters.DNSServerName,
parameters.DNSTCPIPRetryCount,
parameters.DNSUDPRetryCount);
}

if (parameters.SMTPRelayServerName)
{
mailer.SMTPRelayServers().add(parameters.SMTPRelayServerName,
parameters.SMTPPortNumber,
parameters.SMTPServerIPAddress,
parameters.SMTPUserName,
parameters.SMTPPassword);

}

// Add your own code here, then send the message

mercredi 20 avril 2011

How to set value in a field according to another field in a grid of a form

if you want automatically to assign value to field_I  in a grid according to another field_II you can do it in the
modified method of field_II in your dataSource as follows:
public void modified()
{
    ;

    super();

    CategoryTable.CategoryName = Thy_DimensionsNivels::find(

                             CategoryTable.CategoryId).Description;
}

How to display Static fields in a form in Dynamics AX

Simply create display methods in the methods of your form and call them.

mardi 19 avril 2011

How to create method find in a table

Follow this example:

static Thy_DimensionsNivels find(ProjCategoryId _projCategoryId, boolean _forUpdate = false)
{
    Thy_DimensionsNivels   thy_DimensionsNivels = null;
    ;

    Thy_DimensionsNivels.selectForUpdate(_forUpdate);

    if (_projCategoryId)
    {
        select firstonly thy_DimensionsNivels
                index hint DimensionIdx
                    where thy_DimensionsNivels.ConcatNum  == _projCategoryId;
    }

    return thy_DimensionsNivels;
}

Or this one in the inventDim Table 

static public InventDim find(InventDimId inventDimId, boolean _forupdate = false)
{
    InventDim inventDim;
    ;

    if (inventDimId)
    {
        if (_forupdate)
            inventDim.selectForUpdate(_forupdate);

        select firstonly inventDim
            index hint DimIdIdx
            where inventDim.InventDimId  == inventDimId;
    }

    return inventDim;
}

How to create method exist in a table

Follow this example

public static boolean exist(String255 _concatNum)
{
    boolean found;
    ;

    found = (select firstonly
                 RecId
            from
                 Thy_dimensionsNivels
             where
                 Thy_dimensionsNivels.ConcatNum == _concatNum).RecId != 0;

    return found;
}

lundi 18 avril 2011

How to update vendor addresses in Dynamics AX

static void J1A_UpdateVendAddressType(Args _args)
{
VendTable vendTab; // Replace VendTable with CustTable when run this for customers.
DirPartyTable dirPartyTab;
Address addTab;
;
ttsbegin;
while select vendTab
join dirPartyTab
join forupdate addTab
where vendTab.PartyId == dirPartyTab.PartyId &&
addTab.AddrTableId == dirPartyTab.TableId &&
addTab.AddrRecId == dirPartyTab.RecId
{
      if(addTab.Name == 'Birincil Adres')
     {
        addTab.type = AddressType::Payment;
       addTab.update();
     }
}
ttscommit;
}

How to import vendors to VendTable in Dynamics AX

Here are the steps:

1. Import vendor records with a PartyID (I used vendor id)

2. Import records into the DirPartyTable

Type = Organisation
Language=EN-GB (for example)
PartyID=VendTable.AccountNum

3. Import records into the Address table (export dirpartytable to get recid)

AddrRecId=DirPartyTable.RecID
AddrTableId=2303 
STREET=address (i.e added char(10)s in excel for carriage returns - I know
there are other ways)

4. Import records into PartyAddressRelationship (export address to get recid)

Status=active
PartyID = vendtable.partyid

5. Import records into PartyAddressRelationshipMapping (export
partyaddressrelationship to get recid)

addressrecid=address.recid
partyaddressrelationshiprecid=partyaddressrelationship.

vendredi 15 avril 2011

How to allow creating in a grid of a form only when choosing value of another field

Try this

public void create(boolean _append = false)
{
     if( InventFamilyId1.valueStr()!= "")
     {
        super(_append);
     }
     else
     {
        Warning("@THY101");
     }
}

How to initilize a field in a form when all records in the grid are deleted

You can use this

public void delete()
{
    super();
    if (!Thy_InventItemPrintParameters::exist(Thy_InventItemPrintParameters.ItemId))
    {
        InventFamilyId1.text("");
        InventFamilyId1.enabled(Noyes::Yes);
        InventFamilyId1.mandatory(Noyes::Yes);
    }
}

mardi 12 avril 2011

How to personalize go to main table functionality

In forms you may disable go to main table functionality by overriding
datasource field jumpRef() method and commenting super();
public void jumpRef()
{
//    super();
}  
for example we can do this if you want to send parameters to the form you are calling when clicking on : 
go to the main table 
public void jumpRef()
{
    Args            args;
    FormRun         formRun;
    FormBParams     formBParams = new FormBParams();

    ;

    args = new args();

    // If we want pass just simple string we can use 'parm' method of 'Args' class
    args.parm(ctrlInventTable_ItemId.text() );
    args.parmObject( formBParams );

    args.name( formstr( Thy_InventItemPageLine ) );
    formRun = classFactory.formRunClass( Args );
    formRun.init();
    formrun.run();
    formrun.wait();
   // super();
}
In the overrided init method of the form you're going to call :
you can call your parameter  
public void init()
{
    InventTable     inventTableRecord;
    ;

    super();

    if( element.args().parm())
    {
        Thy_InventItemPrint_ItemId.text(element.args().parm());
    }
}

lundi 11 avril 2011

How to add a table and join it to another in a form

For example when you need to get fields from a table joined to a table inventTable for example in your form, just create your relation in that table, then add it in the form , set it joinSource proprety  to inventTable , specify the appropriate LinkType, set the two propreties: InsertAtEnd to no if you don't want to create a new row when scrolling through records and getting to the bottom, and InsertIfEmpty to no if you do not want AX to automatically add a new record if no records exist.
Override the method validateWrite in your dataSource and write this code form example to validate the join SourceProprety : 

boolean validateWrite()
{
    ;
    Thy_InventItemPrint1.ItemId = inventTable.ItemId;
    return super();
}