Skip to content

Automatically remove unbound elements

Greg Bowler edited this page Jul 19, 2023 · 2 revisions

When an element has a data-bind attribute, if there is nothing bound to the element, the element's default content is preserved - this is a feature to allow an element's default state to be defined in the HTML.

It is sometimes useful to only display elements when they have data bound to them. A common example is when there's an error in a form; if there is no error message bound, the element containing the error message should ideally not exist anywhere in the document.

Similar to the data-list attribute, when dealing with single elements the data-element attribute can be added to any element, which will automatically remove the element if it doesn't get bound before the cleanupDocument() function is called. In WebEngine applications, the document is cleaned automatically after your code has executed.

Example html:

<h1>Log in to the system</h1>
<form method="post">

<!-- 
note this DIV is used to show an error with the form, but it should be removed
of there is no error bound by PHP.
-->

	<div data-element data-bind:text="error">Error message goes here</div>
	
	<label>
		<span>Your email address:</span>
		<input name="email" type="email" required />
	</label>
	<label>
		<span>Your password:</span>
		<input name="password" type="password" required />
	</label>
	
	<button name="do" value="login">Log in!</button>
</form>

Example PHP:

function example(
	DocumentBinder $binder,
	Input $input,
	Response $response,
	ExampleAuthentication $auth,
):void {
	try {
		$auth->login($input->getString("email"), $input->getString("password"));
		$response->redirect("/admin/settings/");
	}
	catch(ExampleAuthenticationException $e) {
		$binder->bindKeyValue("error", $e->getMessage());
	}
}

In the above example, the error message is defined in the HTML, but if there is no error, the element will be removed from the DOM automatically.

The PHP passes the example authentication system the user email and password, and if it succeeds, the user is redirected to the admin page.

If the authentication system throws an exception, the exception message is bound to the "error" bind key, and the error message element is not removed from the page.


Next, learn how to bind tabular data into HTML tables.