Flex: force focus on parent change

By , last updated October 27, 2019

I was trying to solve a problem of resetting a focus if the parent changes. I had different buttons that show the same .mxml-form but with different data. The problem was that I needed the focus to be on the first date-field whenever the form is shown so that the user can begin typing data right away.

<mx:HBox>
       <mx:Button id="noData" click="showPanelWithNoData()" />
       <mx:Button id="someData" click="showPanelWithSomeData()" />
       <mx:Button id="withData" click="showPanelWithData()" />

       <myCustomForm:DataForm width="100%" />
</mx:HBox>

So for each time one of the buttons is pushed I need the focus to be on myDate-field. To solve the problem I used “updateComplete“-property of the field.

DataForm.mxml

<?xml version="1.0" encoding="utf-8"?>
<DataForm
    xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script>
        <![CDATA[
            import mx.managers.FocusManager;

            private function resetFocus():void {
                if (focusManager != null && myDate.focusManager != null) {
                    focusManager.setFocus(myDate);
                }
            }
        ]]>
    </mx:Script>

    <mx:FormItem>
        <mx:TextField id="myDate"
            updateComplete="resetFocus()"/>
    </mx:FormItem>

</DataForm>