Sorry guys my title might not really explain what i want to achieve, i have an array of countries and i want to save it into the data base below is my code
public function actionCountries(){
$countries = array("AF" => "Afghanistan",
"AX" => "Ă…land Islands",
"AL" => "Albania",
"DZ" => "Algeria",
"AS" => "American Samoa",
"AD" => "Andorra",
"AO" => "Angola",
"AI" => "Anguilla",
"AQ" => "Antarctica",
"AG" => "Antigua and Barbuda",
"AR" => "Argentina",
"AM" => "Armenia",
"AW" => "Aruba",
"AU" => "Australia",
"AT" => "Austria",
"AZ" => "Azerbaijan",
"BS" => "Bahamas",
"BH" => "Bahrain",
"BD" => "Bangladesh",
"BB" => "Barbados",
"YE" => "Yemen",
"ZM" => "Zambia",
"ZW" => "Zimbabwe");
$model = new Country();
foreach($countries as $code => $name){
$model->code = $code
$model->code = $name
if($model->save()){
echo $model->countryId;
}
}
}
i want to save all of the country into the database on one single click, but the result i got is empty, if i supply a false argument to the save() method i got the last element of the array saved into the database like below
$model = new Country();
foreach($countries as $code => $name){
$model->code = $code
$model->code = $name
if($model->save(false)){
echo $model->countryId;
}
}
this code will save only the last element in the array while the first code did nothing
Any help on this thanks
It's because
$model = new Country();
is outside of the loop so you are saving the same model over and over again. Move this inside the loop.
By the way - it's not efficient. Take a look at batchInsert() method for more memory-friendly way to do it.
Related
I feed JSON to some webhook to trigger a notification (M$ Teams). This works well. However, I want to extend my Perl script: I need to add a new node to my "messagecard" construct on a certain condition.
E.g. I defined this:
my $payload={};
$payload = {
'#type' => 'MessageCard',
'#context' => 'http://schema.org/extensions',
themeColor => $event{COLOR},
text => $event{SERVICEOUTPUT},
sections => [{
facts => [{
name => 'Type',
value => "$event{NOTIFICATIONTYPE} $event{ADDITIONALINFO}"
},
]
}],
potentialAction => [{
'#type' => "OpenUri",
name => "View Monitoring",
targets => [{
os => "default",
uri => $naemon_url
}]
}]
};
$ua = LWP::UserAgent->new;
my $req = POST($opt_webhook
, 'Content-Type' => 'application/json; charset=UTF-8'
, 'Content' => encode_json($payload)
);
my $resp = $ua->request($req);
And if (conditon), I want to extend this as follows (order is important):
$payload = {
'#type' => 'MessageCard',
'#context' => 'http://schema.org/extensions',
themeColor => $event{COLOR},
text => $event{SERVICEOUTPUT},
sections => [{
facts => [{
name => 'Type',
value => "$event{NOTIFICATIONTYPE} $event{ADDITIONALINFO}"
},
]
}],
potentialAction => [{
'#type' => "OpenUri",
name => "View Monitoring",
targets => [{
os => "default",
uri => $naemon_url
}]
},
{
'#type' => "OpenUri",
name => "Notes (Logs, Docs,..)",
targets => [{
os => "default",
uri => $event{SERVICENOTESURL}
}]
}]
};
I am unsure how this can be achieved. Can anyone please provide wisdom how to tackle this?
You can push into the array reference that you've got inside your potentialAction key. In order to do that, you need to dereference it as an array.
my $payload = {
'#type' => 'MessageCard',
potentialAction => [{
name => "View Monitoring",
targets => [{
os => "default",
}]
}]
};
if ($maybe) {
push #{ $payload->{potentialAction} }, {
name => "Notes (Logs, Docs,..)",
targets => [{
os => "default",
}]
};
}
If your Perl version is 5.24 or newer you can also use postfix dereferencing, which some people find easier to read.
push $payload->{potentialAction}->#*, ...
See perlref and perlreftut for more information.
I'm currently working on internationalization for a website using Yii2.
Usually, I use it like this:
Yii::t('frontend', 'Do you have something to eat?')
Then, I have two folders in common\messages called en-EN and id-ID. Each has frontend.php inside of it.
en-EN/frontend.php
return [
];
id-ID/frontend.php
return [
'Do you have something to eat?' => 'Ada yang bisa dimakan?'
];
It works fine, but I don't think it's practical because the sentence is too long and one character miss will not work.
So I tried using something like this:
Yii::t('frontend', 'My.Random.Sentence');
en-EN/frontend.php
return [
'My.Random.Sentence' => 'Do you have something to eat?',
];
id-ID/frontend.php
return [
'My.Random.Sentence' => 'Ada yang bisa dimakan?'
];
It only works for id-ID, but when I change back to english, it still displays My.Random.Sentence instead of Do you have something to eat.
This is my config in i18n.php
return [
'sourcePath' => __DIR__. '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR,
'languages' => ['en-EN','id-ID'],
'translator' => 'Yii::t',
'sort' => false,
'removeUnused' => false,
'only' => ['*.php'],
'except' => [
'.svn',
'.git',
'.gitignore',
'.gitkeep',
'.hgignore',
'.hgkeep',
'/messages',
'/vendor',
],
'format' => 'php',
'messagePath' => __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'messages',
'overwrite' => true,
];
And this is in frontend/config/main.php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['lang']))
$_SESSION['lang'] = 'en-US';
return [
// other options
'language' => $_SESSION['lang'],
'sourceLanguage' => 'en-EN',
'components' => [
'i18n' => [
'translations' => [
'frontend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
],
'backend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
],
],
],
],
//other options
];
Is this not possible? What is the correct way for my problem?
By default, i18n component doesn't translate the string when $sourceLanguage and $language are same. Instead it returns the source string.
But fortunately you can force it to translate the strings even when the $sourceLanguage and $language properties are same. To do that you need to set $forceTranslation property of MessageSource to true. You can do it in you frontend/config/main.php like this:
return [
// other options
'components' => [
'i18n' => [
'translations' => [
'frontend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
'forceTranslation' => true,
],
// ...
],
],
],
//other options
];
Hi I encountered a problem. I will record the data I received from the database.
JSON=>
{
"success": true,
"timestamp": 1565251506,
"base": "EUR",
"date": "2019-08-08",
"rates": {
"AED": 4.119657,
"AFN": 87.689574,
"ALL": 121.192477,
"AMD": 533.113395,
"ANG": 1.998509,
"AOA": 398.760307,
"ARS": 51.036305,
"AUD": 1.654423
}
}
After Json decode
array:5 [
"success" => true
"timestamp" => 1565205306
"base" => "EUR"
"date" => "2019-08-07"
"rates" => array:168 [
"AED" => 4.118588
"AFN" => 87.74397
"ALL" => 121.002609
"AMD" => 534.279745
"ANG" => 2.001014
]
]
I want this=> But How do I get quote and rate?
$response = file_get_contents("rate.json");
$datas = json_decode($response, true);
foreach ($datas as $data) {
$rates = new Rate();
$rates->base = $datas['base'];
$rates->quote = 'AED';
$rates->rate = '4.119657';
$rates->save();
}
You're looping over the wrong thing here, you should be looping over the rates and saving the corresponding key and value:
$response = file_get_contents("rate.json");
$data = json_decode($response, true);
foreach ($data['rates'] as $quote => $rate) {
$rates = new Rate();
$rates->base = $data['base'];
$rates->quote = $quote;
$rates->rate = $rate;
$rates->save();
}
I'm use Guzzle for Laravel to send POST for Webservice, but I can't access array to send picture. That is the structed to I need follow:
{
"title": "xxxxxxxxxxxxxxxxx",
"category_id": "XXXX",
"official_store_id": null,
"pictures": [
{
"id": "XXXXX",
"url": "http://mlb-s1-p.mlstatic.com/292325-MLB25432321923_032017-O.jpg",
"secure_url": "https://mlb-s1-p.mlstatic.com/292325-MLB25432321923_032017-O.jpg",
"size": "500x500",
"max_size": "500x500",
"quality": ""
}
],
}
I try to send it like this:
$r = $client->request('POST', 'https://api.mercadolibre.com/items?access_token='.$token->erp_access_token, [
'json' => [
'title' => $name,
'category_id' => $cat2,
'price' => $price,
'currency_id' => 'BRL',
'available_quantity' => $quantity,
'buying_mode' => 'buy_it_now',
'listing_type_id' => 'gold_special',
'condition' => 'new',
'description' => $description,
'pictures' => [
'url' => $image
]
]
]);
Returns the error:
{"message":"body.invalid_field_types","error":"[invalid property type: [pictures] expected List but was JSONObject value (truncated...)
I read the Guzzle docs, but I not found any example for that case.
Any suggestion?
Change your pictures value from this
'pictures' => [
'url' => $image
]
to this
'pictures' => [
['url' => $image]
]
I am using two select2 ajax loading dropdown list using Yii2 kartik widget. I need to change selection of second dropdown while changing selection of first dropdown.
First Dropdown
<?php
$qtnno = '';
$qtn = ServiceQuotation::find()->where(['UDNO' => $model->QTN_UDNO])->one();
if($qtn != null) $qtnno = $qtn->UDNO;
echo $form->field($model, 'QTN_UDNO')->widget(Select2::classname(), [
'initValueText' => $qtnno, // set the initial display text
'options' => ['placeholder' => 'Search for a Quotation ...',
'onchange'=>'
$.getJSON( "'.Url::toRoute('getqtndetails').'", { id: $("#servicejobcard-qtn_udno").val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'QTNNO').'" ).val( data.qtnno );
$( "#'.Html::getInputId($model, 'QTNDATE').'" ).val( data.qtndate );
$( "#'.Html::getInputId($model, 'PCODE').'" ).select2({ data: [{id: data.pcode, text: data.pname}]});;
$( "#'.Html::getInputId($model, 'PCODE').'" ).select2("val",data.pcode);
$( "#'.Html::getInputId($model, 'PROJECTNAME').'" ).val( data.projectname );
}
);'
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => $urlQtn,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(data) { return data.text; }'),
'templateSelection' => new JsExpression('function (data) { return data.text; }'),
],
]);
?>
Second Drop Down
<?php
$cusName = empty($model->PCODE) ? '' : Customer::findOne($model->PCODE)->PNAME;
echo $form->field($model, 'PCODE')->widget(Select2::classname(), [
'initValueText' => $cusName, // set the initial display text
'options' => ['placeholder' => 'Search for a Customer ...',
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(party) { return party.text; }'),
'templateSelection' => new JsExpression('function (party) { return party.text; }'),
],
]);
?>
Using the above code i'm able to change the selection in second dropdown. But after the change, i'm not able to make selection in second dropdown.
Please help...
Try to use onchange event this way:
[
'options' => [],
// other settings
'pluginEvents' => [
'change' => "function() { alert('change'); }",
]
]
You can find additional information on that page http://demos.krajee.com/widget-details/select2
If you are not restricted to using only Select2 widget, I would suggest you use the Kartik V's DepDrop Widget specifically created for dependent drop-downs.
Since you have not given a lot of context to what your code is actually doing, I am giving a simple 2 level dependency example (slightly modified version of example given in Kartik V's depdrop widget page).
/*
* 2-level dependency example
*/
// THE VIEW
use kartik\widgets\DepDrop;
// Parent
echo $form->field($model, 'cat')->dropDownList($catList, ['id'=>'cat-id']);
// Dependent Dropdown (Child)
echo $form->field($model, 'subcat')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'depends'=>['cat-id'],
'placeholder'=>'Select...',
'url'=>Url::to(['/site/subcat'])
]
]);
// THE SITE CONTROLLER (/site/subcat)
public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = self::getSubCatList($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
The above code can be customized to your requirements.
Here is the link for more details: http://demos.krajee.com/widget-details/depdrop
you can add this kind of query to make the job.
$cusname=QtnUdno::find()->select('PCODE')->where(['UDNO'=>$model->QTN_UDNO])->one();