Why do I get an error related to a controller when I created a custom module?
-
25-02-2021 - |
Question
I created custom module following the Creating a custom module on Drupal tutorial.
The teacher of this tutorial demonstrated how you can create a custom module that displays on the page Hello world
. But I have a slightly more difficult task. I need to create a custom module that will display the weather on the page, receiving data using API, like this.
17.52
1016
London
What I did.
I created the weather.info.yml file.
name: Weather module
description: Weather module
core: 8.x
type: module
package: Weather
I created the weather.routing.yml file.
weather.weather_page:
path: '/weather'
defaults:
_controller: '\Drupal\weather\Controller\WeatherPage::getWeather'
requirements:
_permission: 'access content'
In src/Controller, I created the WeatherPage.php file.
namespace Drupal\weather\Controller;
class WeatherPage
{
public function getWeather($city)
{
$response = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q='.$city.',uk&appid=32ae008b1c7259324aa50450687fabf5&units=metric');
$jsn = json_decode($response);
echo $jsn->main->temp;
echo '<br>';
echo $jsn->main->pressure;
echo '<br>';
echo $city;
}
}
$class = new WeatherPage();
$class->getWeather('London');
?>
I get an error related to the controller.
How do I fix this error?
P.S. One forum user writes that the problem may be due to:
- The controller must return the array
- No code should be behind the class
I'm a Drupal newbie.
Solution
You need to add the parameter to the path. Change this:
path: '/weather'
To this:
path: '/weather/{city}'
Note that the parameter name {city}
must be expressed as the parameter $city
in your callback (which you've done). If you for exampled changed the function definition to getWeather($c)
, you would get an error.
Also, you need to remove this code:
$class = new WeatherPage();
$class->getWeather('London');
?>
And finally, you'll need to return a render array. Change this:
echo $jsn->main->temp;
To this:
return [
'#markup' => $jsn->main->temp,
];