
Recherche avancée
Autres articles (21)
-
Création définitive du canal
12 mars 2010, parLorsque votre demande est validée, vous pouvez alors procéder à la création proprement dite du canal. Chaque canal est un site à part entière placé sous votre responsabilité. Les administrateurs de la plateforme n’y ont aucun accès.
A la validation, vous recevez un email vous invitant donc à créer votre canal.
Pour ce faire il vous suffit de vous rendre à son adresse, dans notre exemple "http://votre_sous_domaine.mediaspip.net".
A ce moment là un mot de passe vous est demandé, il vous suffit d’y (...) -
Les tâches Cron régulières de la ferme
1er décembre 2010, parLa gestion de la ferme passe par l’exécution à intervalle régulier de plusieurs tâches répétitives dites Cron.
Le super Cron (gestion_mutu_super_cron)
Cette tâche, planifiée chaque minute, a pour simple effet d’appeler le Cron de l’ensemble des instances de la mutualisation régulièrement. Couplée avec un Cron système sur le site central de la mutualisation, cela permet de simplement générer des visites régulières sur les différents sites et éviter que les tâches des sites peu visités soient trop (...) -
Taille des images et des logos définissables
9 février 2011, parDans beaucoup d’endroits du site, logos et images sont redimensionnées pour correspondre aux emplacements définis par les thèmes. L’ensemble des ces tailles pouvant changer d’un thème à un autre peuvent être définies directement dans le thème et éviter ainsi à l’utilisateur de devoir les configurer manuellement après avoir changé l’apparence de son site.
Ces tailles d’images sont également disponibles dans la configuration spécifique de MediaSPIP Core. La taille maximale du logo du site en pixels, on permet (...)
Sur d’autres sites (3372)
-
How to create a widget – Introducing the Piwik Platform
4 septembre 2014, par Thomas Steur — DevelopmentThis is the next post of our blog series where we introduce the capabilities of the Piwik platform (our previous post was How to create a scheduled task in Piwik). This time you’ll learn how to create a new widget. For this tutorial you will need to have basic knowledge of PHP.
What is a widget in Piwik ?
Widgets can be added to your dashboards or exported via a URL to embed it on any page. Most widgets in Piwik represent a report but a widget can display anything. For instance a RSS feed of your corporate news. If you prefer to have most of your business relevant data in one dashboard why not display the number of offline sales, the latest stock price, or other key metrics together with your analytics data ?
Getting started
In this series of posts, we assume that you have already set up your development environment. If not, visit the Piwik Developer Zone where you’ll find the tutorial Setting up Piwik.
To summarize the things you have to do to get setup :
- Install Piwik (for instance via git).
- Activate the developer mode :
./console development:enable --full
. - Generate a plugin :
./console generate:plugin --name="MyWidgetPlugin"
. There should now be a folderplugins/MyWidgetPlugin
. - And activate the created plugin under Settings => Plugins.
Let’s start creating a widget
We start by using the Piwik Console to create a widget template :
./console generate:widget
The command will ask you to enter the name of the plugin the widget should belong to. I will simply use the above chosen plugin name “MyWidgetPlugin”. It will ask you for a widget category as well. You can select any existing category, for instance “Visitors”, “Live !” or “Actions”, or you can define a new category, for instance your company name. There should now be a file
plugins/MyWidgetPlugin/Widgets.php
which contains already some examples to get you started easily :- class Widgets extends \Piwik\Plugin\Widgets
- {
- /**
- * Here you can define the category the widget belongs to. You can reuse any existing widget category or define your own category.
- * @var string
- */
- protected $category = 'ExampleCompany';
- /**
- * Here you can add one or multiple widgets. You can add a widget by calling the method "addWidget()" and pass the name of the widget as well as a method name that should be called to render the widget. The method can be defined either directly here in this widget class or in the controller in case you want to reuse the same action for instance in the menu etc.
- */
- protected function init()
- {
- $this->addWidget('Example Widget Name', $method = 'myExampleWidget');
- $this->addWidget('Example Widget 2', $method = 'myExampleWidget', $params = array('myparam' => 'myvalue'));
- }
- /**
- * This method renders a widget as defined in "init()". It's on you how to generate the content of the widget. As long as you return a string everything is fine. You can use for instance a "Piwik\View" to render a twig template. In such a case don't forget to create a twig template (eg. myViewTemplate.twig) in the "templates" directory of your plugin.
- *
- * @return string
- */
- public function myExampleWidget()
- {
- $view = new View('@MyWidgetPlugin/myViewTemplate');
- return $view->render();
- }
- }
As you might have noticed in the generated template we put emphasis on adding comments to explain you directly how to continue and where to get more information. Ideally this saves you some time and you don’t even have to search for more information on our developer pages. The category is defined in the property
$category
and can be changed at any time. Starting from Piwik 2.6.0 the generator will directly create a translation key if necessary to make it easy to translate the category into any language. Translations will be a topic in one of our future posts until then you can explore this feature on our Internationalization guide.A simple example
We can define one or multiple widgets in the
init
method by callingaddWidget($widgetName, $methodName)
. To do so we define the name of a widget which will be seen by your users as well as the name of the method that shall render the widget.protected $category = 'Example Company';
public function init()
{
// Registers a widget named 'News' under the category 'Example Company'.
// The method 'myCorporateNews' will be used to render the widget.
$this->addWidget('News', $method = 'myCorporateNews');
}
public function myCorporateNews()
{
return file_get_contents('http://example.com/news');
}This example would display the content of the specified URL within the widget as defined in the method
myCorporateNews
. It’s on you how to generate the content of the widget. Any string returned by this method will be displayed within the widget. You can use for example a View to render a Twig template. For simplification we are fetching the content from another site. A more complex version would cache this content for faster performance. Caching and views will be covered in one of our future posts as well.Did you know ? To make your life as a developer as stress-free as possible the platform checks whether the registered method actually exists and whether the method is public. If not, Piwik will display a notification in the UI and advice you with the next step.
Checking permissions
Often you do not want to have the content of a widget visible to everyone. You can check for permissions by using one of our many convenient methods which all start with
\Piwik\Piwik::checkUser*
. Just to introduce some of them :// Make sure the current user has super user access
\Piwik\Piwik::checkUserHasSuperUserAccess();
// Make sure the current user is logged in and not anonymous
\Piwik\Piwik::checkUserIsNotAnonymous();And here is an example how you can use it within your widget :
public function myCorporateNews()
{
// Make sure there is an idSite URL parameter
$idSite = Common::getRequestVar('idSite', null, 'int');
// Make sure the user has at least view access for the specified site. This is useful if you want to display data that is related to the specified site.
Piwik::checkUserHasViewAccess($idSite);
$siteUrl = \Piwik\Site::getMainUrlFor($idSite);
return file_get_contents($siteUrl . '/news');
}In case any condition is not met an exception will be thrown and an error message will be presented to the user explaining that he does not have enough permissions. You’ll find the documentation for those methods in the Piwik class reference.
How to test a widget
After you have created your widgets you are surely wondering how to test it. First, you should write a unit or integration test which we will cover in one of our future blog posts. Just one hint : You can use the command
./console generate:test
to create a test. To manually test a widget you can add a widget to a dashboard or export it.Publishing your Plugin on the Marketplace
In case you want to share your widgets with other Piwik users you can do this by pushing your plugin to a public GitHub repository and creating a tag. Easy as that. Read more about how to distribute a plugin.
Advanced features
Isn’t it easy to create a widget ? We never even created a file ! Of course, based on our API design principle “The complexity of our API should never exceed the complexity of your use case.” you can accomplish more if you want : You can clarify parameters that will be passed to your widget, you can create a method in the Controller instead of the Widget class to make the same method also reusable for adding it to the menu, you can assign different categories to different widgets, you can remove any widgets that were added by the Piwik core or other plugins and more.
Would you like to know more about widgets ? Go to our Widgets class reference in the Piwik Developer Zone.
If you have any feedback regarding our APIs or our guides in the Developer Zone feel free to send it to us.
-
How to Choose the Optimal Multi-Touch Attribution Model for Your Organisation
13 mars 2023, par Erin — Analytics Tips -
Revision 29159 : Tester une autre méthode pour que le multilinguisme fonctionne à la ...
13 juin 2009, par marcimat@… — LogTester une autre méthode pour que le multilinguisme fonctionne à la création de la mutualisation. Ca me parait plus portable.