> For the complete documentation index, see [llms.txt](https://uccello.gitbook.io/doc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://uccello.gitbook.io/doc/the-basics/widget.md).

# Widget

## Definition

A widget is an autonomous graphical element you can add to different pages of your application. In general widgets are placed on the Home Page, or in the Summary View of a record. But it is possible to place widgets on any page of the application.

Uccello use the [Laravel Widgets](https://github.com/arrilot/laravel-widgets) library for managing widgets. For more information, please refer to its documentation.

## Default Widgets

By default, Uccello offers 2 widgets you can use with your modules:

* SummaryFields
* RelatedListWidget

These widgets allow to display some information in the Summary View of a record.

### SummaryFields

Thanks to this widget you can quickly view the summary of a record, displaying the value of the fields of your choice.

![](/files/-LtaXzXTHPHInfab1dTP)

Here is an example for using this widget with a module:

```php
<?php

use Uccello\Core\Models\Module;
use Uccello\Core\Models\Widget;

$module = Module::where('name', 'person')->first();

// Add summary field widget
$widget = Widget::where('label', 'widget.main_fields')->first();
$module->widgets()->attach($widget->id, ['data' => json_encode(['fields' => ['name', 'email', 'phone', 'opt_in', 'activated', 'image']]), 'sequence' => 0]);
```

{% hint style="info" %}
The `data` attribute must contain a json string listing the module's fields you want to display.
{% endhint %}

### RelatedListWidget

This widget allows to display a [Related List](/doc/the-basics/related-list.md) in the Summary View of a record. It is useful to display several Related Lists in the same page.

![](/files/-LtaYh4W5ONXQ_nfYsXM)

Here is an example for using this widget with a module:

```php
<?php

use Uccello\Core\Models\Module;
use Uccello\Core\Models\Widget;

$module = Module::where('name', 'person')->first();

// Add relatedlist widget
$widget = Widget::where('label', 'widget.relatedlist')->first();
$relatedlist = $module->relatedlists->where('label', 'relatedlist.contacts')->first();
$module->widgets()->attach($widget->id, ['data' => json_encode(['id' => $relatedlist->id]), 'sequence' => 1]);
```

{% hint style="info" %}
The `data` attribute must contain a json string with the id of the related list you want to use.
{% endhint %}

## Create widgets

Thanks to 2 tutorials we will learn to create new widgets.

### Home Page widget

We will display on the home page a widget for displaying the number of Users total and only in the current domain.&#x20;

* **Make the widget**

You can easily create new widgets. To do this launch the following command:

```bash
php artisan make:widget DashboardUserWidget
```

This command create 2 files:

1. `app/Widgets/DashboardUserWidget.php`: The widget's controller
2. `resources/views/widgets/dashboard_user_widget.blade.php`: The widget's view

* **Override the Home Page view**

First of all, we'll [override](/doc/customize-your-application/overriding.md#override-a-view) the Home Page for displaying the widget:

Create a file located at `resources/views/uccello/modules/home/index/main.blade.php` to override the view.

```bash
@extends('uccello::modules.home.index.main')

@section('content')
    @widget('DashboardUserWidget', ['domain' => $domain])
@endsection
```

We pass the current domain object to the widget using the variable `$domain` available in all pages of Uccello.

* **Configure the Widget's controller**

Add the following code to the file located at `app/Widgets/DashboardUserWidget.php`:

```php
<?php

namespace App\Widgets;

use App\User;
use Arrilot\Widgets\AbstractWidget;

class DashboardUserWidget extends AbstractWidget
{

    ...

    public function run()
    {
        $totalUsersCount = User::count();
        $domainUsersCount = User::inDomain($this->config['domain'])->count();
    
        return view('widgets.dashboard_user_widget', [
            'config' => $this->config,
            'totalUsersCount' => $totalUsersCount,
            'domainUsersCount' => $domainUsersCount
        ]);
    }
}
```

We can use `$this->config['domain']` to get the domain object passed to the widget.\
We use the `inDomain()` scope for retrieving only the users created in the current domain.\
Then we pass `$totalUsersCount` and `$domainUsersCount` variables to the widget's view.

* **Configure the Widget's view**

Add the following code to the file located at `resources/views/widgets/dashboard_user_widget.blade.php`:

```markup
<div class="row">
    {{-- Total Users --}}
    <div class="col s12 m6 l3">
        <div class="card horizontal info-box">
            <div class="icon primary">
                <i class="material-icons">person</i>
            </div>
            <div class="card-stacked">
                <div class="card-content">
                    <div class="text uppercase">Total</div>
                    <div class="number count-to" data-from="0" data-to="{{ $totalUsersCount }}" data-speed="1000" data-fresh-interval="20">{{ $totalUsersCount }}</div>
                </div>
            </div>
        </div>
    </div>

    {{-- Domain Users --}}
    <div class="col s12 m6 l3">
        <div class="card horizontal info-box">
            <div class="icon green">
                <i class="material-icons">person</i>
            </div>
            <div class="card-stacked">
                <div class="card-content">
                    <div class="text uppercase">Current domain</div>
                    <div class="number count-to" data-from="0" data-to="{{ $domainUsersCount }}" data-speed="1000" data-fresh-interval="20">{{ $domainUsersCount }}</div>
                </div>
            </div>
        </div>
    </div>
</div>
```

{% hint style="warning" %}
It is better to use translation for displaying "Total" and "Current domain" strings.
{% endhint %}

Our new dashboard widget is ready an it's displaying the number of users! Thanks to the [jquery-countTo library](https://github.com/mhuggins/jquery-countTo), the numbers of users are animated.

![](/files/-Lte4Ep8Cp5NeolynolY)

####

### Summary View widget

Although Summary View widgets can be created and used in the same way as Home Page widgets, Uccello provides a way to link a widget to a module and automatically add it to the module's Summary View.

We will create a widget that will be referenced in the database and that can be easily used with any module. The widget will display a list of all domains in which the user has a role.

* **Make the widget**

You can easily create new widgets. To do this launch the following command:

```bash
php artisan make:widget UserRolesWidget
```

This command create 2 files:

1. `app/Widgets/UserRolesWidget.php`: The widget's controller
2. `resources/views/widgets/user_roles_widget.blade.php`: The widget's view

* **Configure the Widget's controller**

Add the following code to the file located at `app/Widgets/UserRolesWidget.php`:

```php
<?php

namespace App\Widgets;

use App\User;
use Arrilot\Widgets\AbstractWidget;
use Uccello\Core\Models\Domain;

class UserRolesWidget extends AbstractWidget
{
    ...

    public function run()
    {
        $user = User::find($this->config['record_id']);

        $rolesOnDomains = collect();
        foreach (Domain::all() as $domain) {
            $rolesOnDomain = $user->rolesOnDomain($domain);

            if (count($rolesOnDomain) > 0) {
                $rolesOnDomains[$domain->name] = $rolesOnDomain;
            }
        }

        return view('widgets.user_roles_widget', [
            'config' => $this->config,
            'domain' => ucdomain($this->config['domain']),
            'module' => ucmodule($this->config['module']),
            'data' => (object) $this->config['data'],
            'record' => $user,
            'label' => $this->config['data']->label ?? $this->config['labelForTranslation'],
            'rolesOnDomains' => $rolesOnDomains
        ]);
    }
}
```

{% hint style="info" %}
As you can see in the file located at [vendor/uccello/uccello/resources/views/modules/default/detail/summary.blade.php](https://github.com/uccellolabs/uccello/blob/master/resources/views/modules/default/detail/summary.blade.php), several variable are passed to the widget and are available in `$this->config`.&#x20;
{% endhint %}

* **Configure the widget's view**

Add the following code to the file located at `resources/views/widgets/user_roles_widget.blade.php`:

```markup
<div class="row">
  <div class="col s12">
    <div class="card">
      <div class="card-content">
        {{-- Title --}}
        <span class="card-title">
          {{-- Icon --}}
          <i class="material-icons left primary-text">lock</i>

          {{-- Label --}}
          {{ trans($label) }}
        </span>

        <div class="row">
          <ul class="collection with-header">
            @forelse ($rolesOnDomains as $domainName => $roles)
              {{-- Domain name --}}
              <li class="collection-header"><b>{{ $domainName }}</b></li>
  
              {{-- List of roles --}}
              @foreach ($roles as $role)
              <li class="collection-item">{{ $role->name }}</li>
              @endforeach
            @empty
              {{-- No roles message --}}
              <li class="collection-item red-text center-align">{{ uctrans('widget.user_roles.no_role') }}</li>
            @endforelse
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>
```

* **Add the translations**

Create a file located at `resources/lang/en/widgets.php` and add it the following code:

```php
<?php

return [
    'widget' => [
        'user_roles' => 'User\'s roles',
    ]
];
```

* **Add the widget into the database**

First of all we will create a migration to reference the widget in the database and link it with the User module.

Launch the following command to create the migration:

```bash
php artisan make:migration add_user_roles_widget
```

Add this code into the migration file freshly created:

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Uccello\Core\Models\Module;
use Uccello\Core\Models\Widget;

class AddUserRolesWidget extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Add the widget into the list of widgets
        $widget = Widget::create([
            'label' => 'widget.user_roles',
            'type' => 'summary',
            'class' => 'App\Widgets\UserRolesWidget',
            'data' => null
        ]);

        // Link the widget to the User module
        $module = Module::where('name', 'user')->first();
        $module->widgets()->attach($widget->id, [ 'sequence' => 0]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Widget::where('label', 'widget.user_roles')
            ->where('type', 'summary')
            ->where('class', 'App\Widgets\UserRolesWidget')->delete();
    }
}
```

{% hint style="info" %}
When you attach a widget to a module, you can pass the following pivot values:

* `sequence`: Order in which to display the widget in the Summary View
* `data`: A json encoded object to pass to the widget's controller. These data can be retrieved using `(object) $this->config['data']`.
  {% endhint %}

Launch the migration with the following command:

```bash
php artisan migrate
```

Our new widget is ready an it's displaying the roles of a user in the Summary View of the record!

![](/files/-LteJ5B2T4xstK1oODfd)

## Properties

| Attribute | Type   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Default |
| --------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-----: |
| **label** | string | Widget's label. To translate it, create a localization file located at `resources/lang/{lang_code}/widgets.php` and add your translations.                                                                                                                                                                                                                                                                                                                                                                                                                                                 |         |
| **type**  | string | Type of widget. For the moment only the `summary` option is available by default. It allows to display automatically the widget into a Summary View of a module.                                                                                                                                                                                                                                                                                                                                                                                                                           |         |
| **class** | string | Path to the widget's controller generated by the command `php artisan make:widget WidgetName`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |         |
| **data**  | array  | <p>Data to pass to the widget. </p><ul><li>You can use <code>label</code> to override the way how the label is made. By default the full label generated is<code>$this->languagePackage.'widgets.'.$this->label</code> .<br></li><li><p>In case or you are developing an external package, you must use <code>package</code> to set the name of your external package in which the widget is located (e.g. <code>acme/my-package</code>).</p><p>This attribute is only useful for making sharable modules, installable with <a href="https://getcomposer.org/">composer</a>.</p></li></ul> |  `null` |
