OOUI/PHP examples

From mediawiki.org

If you are using OOUI:

A more extensive set of most PHP widget examples is available in the source code repository. When you clone the repository and/or install it using composer, take a look at /demos/widgets.php.

Setup the library[edit]

Before you display any OOUI widgets, you need to set up the library by calling the following functions:

OOUI\Theme::setSingleton( new WikimediaUITheme() ); // or: new ApexTheme()
OOUI\Element::setDefaultDir( 'ltr' );               // or: 'rtl'

You also need to load the CSS:

<!-- Use 'wikimediaui' or 'apex' -->
<link rel="stylesheet" href="dist/oojs-ui-core-wikimediaui.css">   <!-- or: .rtl.css -->
<link rel="stylesheet" href="dist/oojs-ui-images-wikimediaui.css"> <!-- or: .rtl.css-->

Creating a button[edit]

To create a button, use the OOUI\ButtonWidget class. The first and only argument to a button's constructor is its configuration.

$btn = new OOUI\ButtonWidget( [
    'label' => 'Click me!'
] );

Before the button is converted to HTML and emitted, the label, target and href can be changed using the setTarget and setHref methods.

$btn
    ->setLabel( 'Still click me!' )
    ->setTarget( 'blank' )
    ->setHref( 'https://mediawiki.org/' );

The button is now created, and has a label which reads "Still click me!", but is not yet visible to the user, as it must first converted to HTML and echoed into the document:

echo $btn;

Adding JavaScript behaviors[edit]

Setting the href property will ensure that clicking the button loads a new PHP page. But if you want to use the technique of progressive enhancement to add client-side JavaScript behaviors to the button, you can "infuse" the object on the client side with the JavaScript OO.ui.infuse method. You must set the infusable property when the widget is configured:

<?php
$btn = new OOUI\ButtonWidget( [
    'infusable' => true,
    'label' => 'Click me!',
    'target' => 'blank',
    'href' => 'https://www.mediawiki.org/'
] );
echo $btn;

Then you'd load some client-side JavaScript to enhance this widget:

// The argument here must be either a string matching the 'id' you gave the widget in the PHP code,
// or jQuery node representing the widget you created in the PHP code.
var myButton = OO.ui.infuse( 'my-button' );
// Add new client-side actions.
myButton.on( 'click', function () {
    window.alert( 'I was clicked!' );
} );

Playing it safe[edit]

For extra type safety, you can use the infuse method of the specific type of widget you expect. That is:

var myButton = OO.ui.ButtonWidget.static.infuse( 'my-button' );

This will throw an exception at runtime if PHP and JavaScript disagree about the widget type of my-button. (As of 2015-05, this is not implemented yet, but will be in the future.)