Pages

Thursday, September 19, 2013

Calling methods on a caller Dynamics AX form

To call methods on a caller form from another form or a class for example, you have to fetch the caller from the args object, keep it as an Object and just then you can call methods in it.

You have to keep it as an Object like the caller method returns it to you, because then the compiler allows you to call methods in a dynamic way. This means that there will be no compile-time checking for the method that you are trying to call, as it happens with any object of type Object in AX, so if you try to call a method that doesn't exist on the form, you'll get a run-time error.


Here's some example code:

Object caller = _args.caller(); 

    // Or if you're in a form:
    // caller = element.args().caller();

    caller.someMethodOnTheForm();


And just to add some defensive code so that you can avoid getting a run-time error, you could add the following validations to the same piece of code:

Object caller = _args.caller();

    if (caller is FormRun && formHasMethod(caller, identifierStr(someMethodOnTheForm)))
    {
        caller.someMethodOnTheForm();
    }

Now you're also checking if the caller is in fact a form, and also if it has the method you're trying to call.

3 comments:

  1. A good a addition would be to first test if the method exists before calling it:
    formHasMethod(caller, identifierStr(someMethodOnTheForm))

    ReplyDelete
    Replies
    1. Hi thwidmer,

      I've added what you suggested to the post.

      Thanks for your feedback!

      Delete
  2. For AX 2009 users change:
    (caller is FormRun)
    To:
    (SysDictClass::isEqualOrSuperclass(classidget(element.args().caller()), classnum(FormRun)))

    Cheers

    ReplyDelete