belicoff
(belicoff)
July 7, 2020, 9:48am
1
Hi,
I have issue with getting parameters from URL to my Yii2 Controller or Model, to send it in post request via WebService.
Ex. URL : https://example.com/?keyword=test&id=1234
My Model Save Function code is :
public function save($keyword)
{
$httpClient = new Client();
$data = [
'civilite' => $this->civility,
'nom' => $this->lastName,
'prenom' => $this->firstName,
'telephone' => $this->phoneNumber,
'email' => $this->emailAddress,
'operateur' => $this->operator,
'tel_domicile' => $this->phone,
'keyword' => $keyword,
];
$preferences = explode(',', $this->preferences);
$index = 0;
foreach ($preferences as $preference) {
$index++;
$data['attente' . $index] = $preference;
}
LeadLogHelper::log($data);
$rawResponse = $httpClient->createRequest()
->setMethod('POST')
->setUrl(\Yii::$app->params['WebserviceUrl'])
->setData($data)
->send();
$response = json_decode($rawResponse->content);
if (!$response->Statut) {
Yii::error('An error occurred while saving the data using the webservice', __METHOD__);
Yii::error($data, __METHOD__);
Yii::error($response, __METHOD__);
}
return $response->Statut == 1 || $response->Message === 'Already exist.';
}
My Controller Sumbit Action is :
public function actionSubmit()
{
$leadModel = new LeadModel();
$data = LeadModelFormHelper::transformDataFormToModel(Yii::$app->request->post());
$leadModel->setAttributes($data);
if (!$leadModel->validate()) {
return $this->sendValidationErrorResponse($leadModel->getErrors());
}
$bestOffer = $leadModel->getBestOffer();
$isSuccessfullySaved = $leadModel->save(Yii::$app->request->get('keyword'));
if (!$isSuccessfullySaved) {
$response = $this->asJson(['errors' => ['webservice' => 'Error while saving the lead']]);
$response->statusCode = 550;
return $response->send();
}
$lastStep = Json::decode(file_get_contents(__DIR__ . '/../config-offers/offers.json'));
$isSuccessfullySent = Yii::$app->mailer->compose(
'offer-summary',
ArrayHelper::merge($leadModel->getAttributes(), $lastStep['offres'][$bestOffer])
)
->setFrom(['noreply@choisirmabox.fr' => 'CHOISIR MA BOX'])
->setTo($leadModel->emailAddress)
->setSubject('choisirmabox.fr - Votre offre')
->send();
if (!$isSuccessfullySent) {
Yii::error("Could not send the email", __METHOD__);
}
return $this->asJson(['offer' => $bestOffer]);
}
The keyword have a NULL value, can any one help me please ?!!
samdark
(Alexander Makarov)
July 7, 2020, 9:49am
2
You’re passing key
but asking for keyword
.
1 Like
belicoff
(belicoff)
July 7, 2020, 9:50am
3
Hi samdark, yes sorry, it’s an example, in my real URL a pass keyword parameter.
samdark
(Alexander Makarov)
July 7, 2020, 9:52am
4
Are you sure https://example.com/?keyword=test&id=1234 actually submits data to actionSubmit()
?
You can learn about it by doing:
public function actionSubmit()
{
var_dump($_GET); die();
1 Like
belicoff
(belicoff)
July 7, 2020, 9:53am
5
Yes they submit already posted values like firstName … but the don’t get the keyword value.
samdark
(Alexander Makarov)
July 7, 2020, 9:55am
6
Would you please provide output of the above code?
1 Like
samdark
(Alexander Makarov)
July 7, 2020, 10:05am
8
Then either you’re not executing correct action (what https://example.com/?keyword=test&id=1234 points to?) or your router is configured incorrectly (what’s in your config?).
1 Like
belicoff
(belicoff)
July 7, 2020, 10:12am
9
Firstly, lot of thanks for your help.
The url points to index, my default router in config file is :
'/<url:.+>' => 'site/index',
'defaultRoute' => 'site/index',
belicoff
(belicoff)
July 7, 2020, 10:18am
10
config file for url
'urlManager' => [
'enableStrictParsing' => true,
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'/' => 'site/index',
'site/submit' => 'site/submit',
'admin' => 'admin/index',
'admin/login' => 'admin/login',
'admin/index' => 'admin/index',
'admin/logout' => 'admin/logout',
// Let Vue Router handle the rest of the routing (yes, 404s as well)
'/<url:.+>' => 'site/index',
'defaultRoute' => 'site/index',
],
],
belicoff
(belicoff)
July 13, 2020, 2:51pm
11
Hi boss,
Here is the error when I try to get the value:
[127.0.0.1][-][643po989kc0hhlq10rj8uii2ee][error][yii\web\HttpException:405]
yii\web\MethodNotAllowedHttpException: Method Not Allowed. This URL
can only handle the following request methods: POST. in
/var/www/html/dist/vendor/yiisoft/yii2/filters/VerbFilter.php:105
Stack trace:
#0 [internal function]: yii\filters\VerbFilter->beforeAction()
#1
/var/www/html/dist/vendor/yiisoft/yii2/base/Component.php(627):
call_user_func()
#2
/var/www/html/dist/vendor/yiisoft/yii2/base/Controller.php(276):
yii\base\Component->trigger()
#3
/var/www/html/dist/vendor/yiisoft/yii2/web/Controller.php(185):
yii\base\Controller->beforeAction()
#4
/var/www/html/dist/vendor/yiisoft/yii2/base/Controller.php(155):
yii\web\Controller->beforeAction()
#5
/var/www/html/dist/vendor/yiisoft/yii2/base/Module.php(528):
yii\base\Controller->runAction()
#6
/var/www/html/dist/vendor/yiisoft/yii2/web/Application.php(103):
yii\base\Module->runAction()
#7
/var/www/html/dist/vendor/yiisoft/yii2/base/Application.php(386):
yii\web\Application->handleRequest()
#8 /var/www/html/dist/web/index.php(15):
yii\base\Application->run()
#9 {main}
2020-07-13 16:30:39
[127.0.0.1][-][643po989kc0hhlq10rj8uii2ee][info][application]
$_GET = [
‘keyword’ => ‘tresdd’
]
$_POST = []
$_FILES = []
$_COOKIE = [
‘cookieConsent’ => ‘analytics=1,advertising=1’
‘cookieConsentTime’ => ‘1585128569458’
]
$_SESSION = [
‘__flash’ => []
]
$_SERVER = [
‘HTTPS’ => ‘on’
‘SSL_TLS_SNI’ => ‘127.0.0.1’
‘HTTP_HOST’ => ‘127.0.0.1’
‘HTTP_CONNECTION’ => ‘keep-alive’
‘HTTP_PRAGMA’ => ‘no-cache’
‘HTTP_CACHE_CONTROL’ => ‘no-cache’
‘HTTP_UPGRADE_INSECURE_REQUESTS’ => ‘1’
‘HTTP_USER_AGENT’ => ‘Mozilla/5.0 (Windows NT 6.1; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116
Safari/537.36’
‘HTTP_ACCEPT’ =>
‘text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/ ;q=0.8,application/signed-exchange;v=b3;q=0.9’
‘HTTP_SEC_FETCH_SITE’ => ‘none’
‘HTTP_SEC_FETCH_MODE’ => ‘navigate’
‘HTTP_SEC_FETCH_USER’ => ‘?1’
‘HTTP_SEC_FETCH_DEST’ => ‘document’
‘HTTP_ACCEPT_ENCODING’ => ‘gzip, deflate, br’
‘HTTP_ACCEPT_LANGUAGE’ => ‘fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7’
‘HTTP_COOKIE’ => 'cookieConsent=analytics=1,advertising=1;
cookieConsentTime=1585128569458
‘PATH’ =>
‘/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin’
‘SERVER_SIGNATURE’ => 'Apache/2.4.29 (Ubuntu) Server at
127.0.0.1 Port 443
’
‘SERVER_SOFTWARE’ => ‘Apache/2.4.29 (Ubuntu)’
‘SERVER_NAME’ => ‘127.0.0.1’
‘SERVER_ADDR’ => ‘127.0.0.1’
‘SERVER_PORT’ => ‘443’
‘REMOTE_ADDR’ => ‘127.0.0.1’
‘DOCUMENT_ROOT’ => ‘/var/www/html/dist/web’
‘REQUEST_SCHEME’ => ‘https’
‘CONTEXT_PREFIX’ => ‘’
‘CONTEXT_DOCUMENT_ROOT’ => ‘/var/www/html/dist/web’
‘SERVER_ADMIN’ => ‘[no address given]’
‘SCRIPT_FILENAME’ =>
‘/var/www/html/dist/web/index.php’
‘REMOTE_PORT’ => ‘57291’
‘GATEWAY_INTERFACE’ => ‘CGI/1.1’
‘SERVER_PROTOCOL’ => ‘HTTP/1.1’
‘REQUEST_METHOD’ => ‘GET’
‘QUERY_STRING’ => ‘keyword=tresdd’
‘REQUEST_URI’ => ‘/?keyword=tresdd’
‘SCRIPT_NAME’ => ‘/index.php’
‘PHP_SELF’ => ‘/index.php’
‘REQUEST_TIME_FLOAT’ => 1594650639.247
‘REQUEST_TIME’ => 1594650639
]
samdark
(Alexander Makarov)
July 13, 2020, 4:22pm
12
It is all in the error. You have a filter in SiteController
that allows only POST request to index
action but making a GET request.
belicoff
(belicoff)
July 13, 2020, 4:32pm
13
And what is the solution please?! remove the behaviors??
belicoff
(belicoff)
July 13, 2020, 4:32pm
14
public function behaviors()
{
return [
'verbs' => [
'class' => \yii\filters\VerbFilter::className(),
'actions' => [
'index' => ['GET'],
'submit' => ['POST','GET'],
],
],
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => $this->_verbs,
'Access-Control-Allow-Headers' => ['content-type'],
'Access-Control-Request-Headers' => ['*'],
],
],
];
}
samdark
(Alexander Makarov)
July 14, 2020, 5:23pm
15
Make sure the action you submit to allows GET.