Search code examples
formsaxaptax++dynamics-ax-2012form-control

How can the visibility of a button in a form be changed dynamically using x++ code?


How can I change the visibility of my button control MyButton?

I have a form MyForm where I want to set the visibility property for my MyButton button control. I used this code in the form's init method:

public void init()
{
    MyTable myTable;
    ;

    while select myTable where myTable.UserId == curUserId()
    {
        if (myTable.FlagField == NoYes::Yes )
        {
            myButton.visible(true);
        }
        if (!myTable.FlagField == NoYes::No )
        {
            myButton.visible(false);
        }
    }

    super();
}

The property AutoDeclaration of MyButton is set to Yes. But when I open the form, I get the following error:

"Failure initializing FormButtonControl object."

I think I have to use the FormButtonControl class, but I no have idea how to do that.


Solution

  • FH-Inway's answer is correct from a code-perspective, but I want to comment that what you're doing is incorrect and won't function properly unless your mineTable only has 1 matching record.

    Currently as written, when the form is instantiated, you basically loop over mineTable and toggle the myButton visible and hidden over and over for every record where mineTable.UserId == curUserId() , then the form is displayed and whatever the last record happens to be.

    That's the difference between while select [table] where [clause] {[code]} and select [table] where [clause];.

    If you only have one record in that table you should change it to:

    MineTable mineTable;
    
    super();
    
    select firstonly mineTable where mineTable.UserId == curUserId();
    if (mineTable)
    {
        if (mineTable.FlagField== NoYes::Yes )
        {
            myButton.visible(true);
        }
        if(!mineTable.FlagField== NoYes::No )
        {
            myButton.visible(false);
        }
    }
    else
    {
        throw error("Record not found or whatever your error should be");
    }