add content to grid on button click

by Gabriel de Souza

HTML

<script id='sap-ui-bootstrap' type='text/javascript' src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js' data-sap-ui-libs="sap.m" data-sap-ui-theme="sap_bluecrystal">    
</script>

<script id="myXml" type="text/xmldata">
<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:layout="sap.ui.layout" displayBlock="true"
		controllerName="myController" xmlns:html="http://www.w3.org/1999/xhtml">
	<App>
        <Page title="Content to Grid" >
		<content>
		
            <Button text="Add content 1" press="onButton1pressed"></Button>
            <Button text="Add content 2" press="onButton2pressed"></Button>
            
            <layout:Grid id="g">
            
            </layout:Grid>
           
		</content>
	    </Page>
    </App>
</core:View>

</script>
<body class='sapUiBody'>
    <div id='content'></div>
</body>

CSS

.myHLayout .sapUiHLayoutChildWrapper {
	vertical-align: middle;
	padding: 0.5rem;
}

JavaScript

sap.ui.controller("myController", {

    onInit: function () {
        this.oGrid = this.byId("g");
    },

    // button event handler
    onButton1pressed: function () {
        // will be added to grid with default grid span (L3 M3 S12)
        this.oGrid.addContent(new sap.m.Label({
            text: "Hello Grid"
        }));
    },
    
    onButton2pressed: function () {

        // some composite ui -> 
        // can be put into some (xml) fragment for better separation
        // here use layoutdata aggregation to span the 12 columns always
        var oUIBlock = new sap.ui.layout.HorizontalLayout({
            content: [
            new sap.m.Label({
                text: "Some Label"
            }), new sap.m.ComboBox({}), new sap.m.Input()]
        }).setLayoutData(new sap.ui.layout.GridData({
            span: "L12 M12 S12"
        })).addStyleClass("myHLayout");
        // end some composite ui

        this.oGrid.addContent(oUIBlock);

    }
});
sap.ui.view({
    viewContent: jQuery('#myXml').html(),
    type: sap.ui.core.mvc.ViewType.XML
}).placeAt("content")