Batch Insert data into database using web services in yii2 error - web-services

I've tried for get data in web services at http://api.rajaongkir.com/dokumentasi/starter. And I was success show data in view browser. When I implementation for insert data with a lot of into database something any wrong. I don't know why.
This code for get data in web service at http://api.rajaongkir.com/dokumentasi/starter. And put in controllers/TestController.php
public function actionGetProvince($id=0)
{
$client = new client();
$addUrl = ($id>0)?'id='.$id:'';
$response = $client->createRequest()
->setFormat(Client::FORMAT_JSON)
->setMethod('get')
->setUrl('http://api.rajaongkir.com/starter/province?'.$addUrl)
->addHeaders(['key' => 'example'])
->send();
if ($response->isOk) {
$content = \Yii\helpers\Json::decode($response->content);
//$content['rajaongkir']['query']
//$content['rajaongkir']['status']
$results = $content['rajaongkir']['results'];
if ($id > 0) {
if (count($results)>0) {
echo $results['province_id'] . ' - ';
echo $results['province'] . '<br>';
}
else {
echo "blank";
}
} else {
foreach ($results as $provinces) {
echo $provinces['province_id']." - ".$provinces['province']."<br>";
}
}
} else {
$content = \Yii\helpers\Json::decode($response->content);
echo $content['rajaongkir']['status']['description'];
}
}
And this code for insert data with a lot of in database, and I put in file same.
Yii::$app->db->createCommand()->batchInsert('province', [
'id_province' => $provinces['province_id'], 'name' => $provinces['province']
])->execute();
And the result error is :
PHP Warning – yii\base\ErrorException : Missing argument 3 for yii\db\Command::batchInsert(), called in C:\wamp\www\basic_yii2\controllers\TestController.php on line 60 and defined

You are not calling batchInsert() properly.
See it in documentation.
public $this batchInsert ( $table, $columns, $rows )
$table string The table that new rows will be inserted into.
$columns array The column names
$rows array The rows to be batch inserted into the table
Example:
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();

Related

Regular expression for laravel username and #tags

how can I set up a Regular expression for #username and #example on post field form, just like Twitter , when a user uses #hashtag in there post I will like to automatically save it to tag table and when a user uses #john symbol I would like to automatically notify the user he /she has been mentioned , please what is the logic behind this I don't have idea on how to start
im getting this error
BadMethodCallException
Method App\Http\Livewire\createPost::tag does not exist.
public function createPost()
{
if (auth()->check()) {
$this->validate();
$posts = Post::create([
'user_id' => auth()->user()->id,
'school_id' => $this->school,
'body' => $this->body,
'is_anon' => $this->is_anon,
$url = \url(route('posts.show', $this->id)),
]);
preg_match_all('/(?<=#)(\w+)/mi', $this->body, $matchedTags, PREG_SET_ORDER, 0);
foreach($matchedTags as $matchedTag) {
if(!$tag = tag::where('name', $matchedTag[0])->first()) {
$tag = tag::create(['name' => $matchedTag[0]]);
}
$this->tags()->attach($tag->id);
}
assuming your input string is $str, you can use these:
preg_match_all('/(?<=#)(\w+)/mi', $str, $atSignMatches, PREG_SET_ORDER, 0);
preg_match_all('/(?<=#)(\w+)/mi', $str, $poundMatches, PREG_SET_ORDER, 0);
and then you can print the $atSignMatches and $poundMatches which are the resulting values.
More info on https://www.php.net/manual/en/function.preg-match-all.php
Update: Steps
These are the steps to extract users and make notifications.
Get Request payload.
Extract Tags (using #)
Create Tag records in table
Extract mentions (using #)
Create notification for mentioners
public function save(Request $request) {
{
$post = Post::create($request->all());
$content = $post->content;
preg_match_all('/(?<=#)(\w+)/mi', $content, $matchedTags, PREG_SET_ORDER, 0);
foreach($matchedTags as $matchedTag) {
if(!$tag = Tag::where('name', $matchedTag[0])->first()) {
$tag = Tag::create(['name' => $matchedTag[0]]);
}
$post->tags()->attach($tag->id);
}
preg_match_all('/(?<=#)(\w+)/mi', $content, $matchedMentions, PREG_SET_ORDER, 0);
foreach($matchedMentions as $matchedMention) {
if($user = User::where('username', $matchedMention[0])->first()) {
$user->notifications()->create([
'post_id' => $post->id,
'type' => "MENTION",
'seen' => false,
'time' => \Carbon\Carbon::now()
]);
}
}
}
Notes:
Make sure to change the tag and notification creation implementation matching your table structure.

laravel-filemanager, Sort by time default

I need load files order by "time DESC" when the iframe of laravel-filemanager is called.
Is posible? I read the code and see that we cant order by time DESC and the code dont have options to configure a default "sort_type"
https://github.com/UniSharp/laravel-filemanager
this is not good idea but it's work for me
i am change the code in vendor/unisharp/laravel-filemanager/public/js/script.js
var sort_type = 'alphabetic';
to
var sort_type = 'time';
if you want to sort date in desc order. change the code in
vendor/unisharp/laravel-filemanager/src/Controllers/ItemsController.php
public function getItems()
{
$currentPage = self::getCurrentPageFromRequest();
$perPage = $this->helper->getPaginationPerPage();
$items = array_merge($this->lfm->folders(), $this->lfm->files());
return [
'items' => array_map(function ($item) {
return $item->fill()->attributes;
}, array_slice($items, ($currentPage - 1) * $perPage, $perPage)),
'paginator' => [
'current_page' => $currentPage,
'total' => count($items),
'per_page' => $perPage,
],
'display' => $this->helper->getDisplayMode(),
'working_dir' => $this->lfm->path('working_dir'),
];
}
with
use Illuminate\Http\Request;
public function getItems(Request $request)
{
$currentPage = self::getCurrentPageFromRequest();
$perPage = $this->helper->getPaginationPerPage();
$files = $this->lfm->files();
if($request->sort_type=='time'){
$files = array_reverse($files);
}
$items = array_merge($this->lfm->folders(), $files);
return [
'items' => array_map(function ($item) {
return $item->fill()->attributes;
}, array_slice($items, ($currentPage - 1) * $perPage, $perPage)),
'paginator' => [
'current_page' => $currentPage,
'total' => count($items),
'per_page' => $perPage,
],
'display' => $this->helper->getDisplayMode(),
'working_dir' => $this->lfm->path('working_dir'),
];
}
i'm change the code in vendor/unisharp/laravel-filemanager/src/traits/LfmHelpers.php
and it's worked
public function sortFilesAndDirectories($arr_items, $sort_type)
{
if ($sort_type == 'time') {
$key_to_sort = 'updated';
} elseif ($sort_type == 'alphabetic') {
$key_to_sort = 'name';
} else {
$key_to_sort = 'updated';
}
return strcmp($a->{$key_to_sort}, $b->{$key_to_sort});
});
return $arr_items;
}
with
public function sortFilesAndDirectories($arr_items, $sort_type)
{
if ($sort_type == 'time') {
$key_to_sort = 'updated';
} elseif ($sort_type == 'alphabetic') {
$key_to_sort = 'name';
} else {
$key_to_sort = 'updated';
}
uasort($arr_items, function ($a, $b) use ($key_to_sort) {
if ( $a->$key_to_sort == $a->$key_to_sort )
return 0;
else if ( $a->$key_to_sort > $a->$key_to_sort)
return -1;
else
return 1;
});
return $arr_items;
}
LFM 1.8:
Also, you can use this method, if you don't want to change the LFM Src code.
First use this command to generate views :
php artisan vendor:publish --tag=lfm_view
Find this file:
ROOT/resources/views/vendor/laravel-filemanager/grid-view.blade.php
and change the cod according the follow:
#if((sizeof($files) > 0) || (sizeof($directories) > 0))
<div class="row">
<!-- -----------------------------------Begin of added block -->
<?php
$file_temp = [];
if($files != null){
foreach ($files as $key => $value) {
$file_temp[$value['updated']] = $value;
}
krsort($file_temp);
$file_temp1 = [];
$i = 0;
foreach ($file_temp as $key => $value) {
$file_temp1[$i] = $value;
$i+=1;
}
$files = $file_temp1;
}
?>
<!-- ---------------------------------------End of added block -->
#foreach($items as $item)
....
...
As you can see, the <?php ?> code block was added.You can use krsort() or ksort() as you want for descending or ascending.
In 2.3 I did next steps
php artisan vendor:publish --tag=lfm_view
Then you can find file
ROOT/resources/views/vendor/laravel-filemanager/grid-view.blade.php
And after incuding
<script>{!! \File::get(base_path('vendor/unisharp/laravel-filemanager/public/js/script.js')) !!}</script>
I added one line of js
sort_type = 'time';
But files sorts from the oldest to the newest. Thast's why I redefined routes and ItemsController

Get result from vTiger webservice

I am writing a wordpress-plugin which queries data from the vTiger Webservice-API. I read the tutorial (https://wiki.vtiger.com/index.php/Webservices_tutorials#QueryResult) and know the reference (https://wiki.vtiger.com/index.php/Webservice_reference_manual). In the tutorial the use Zend-JSON and HTTP_Client. I use cURL (because it was installed and I thought it was worth a try to use before I install other utilities). It works quite well and I am able to Login to vTiger with our API-User and send the queries. What I receive is something like this:
array(2) {
["success"]=>
bool(true)
["result"]=>
array(4) {
["sessionName"]=>
string(21) "4d103e2058f9d365c22ff"
["userId"]=>
string(4) "19x9"
["version"]=>
string(4) "0.22"
["vtigerVersion"]=>
string(5) "6.5.0"
}
}
Looks very good to me but the Thing I am missing is the actual data from my query.
This is my PHP-Code:
$vtiger->initCurl();
$challengeToken = $vtiger->getChallengeToken();
$sessionId = $vtiger->getSessionId($challengeToken);
$result = $vtiger->query($sessionId, "SELECT firstname FROM 'Contacts' WHERE lastname = 'XXX';");
$wpdb->replace( $wpdb->prefix.$_CONFIG['dbtable'], array( 'id' => 1, 'syncfields' => $result), array('%d', '%s') );
$vtiger->logout($sessionId);
$vtiger->closeCurl();
$result = json_decode($result, true);
return var_dump(($result['success']) ? $result : "Error");
What am I missing to get the firstname (or any other value from the vTiger-DB)?
In the Code I am just writing the Response to the wp-db (extra-Table).
Thanks,
Nico
Vtiger Result Return in array format. you should change your code
$vtiger->initCurl();
$challengeToken = $vtiger->getChallengeToken();
$sessionId = $vtiger->getSessionId($challengeToken);
$result = $vtiger->query($sessionId, "SELECT firstname FROM 'Contacts' WHERE lastname = 'XXX';");
$syncfield = result['0'];
$wpdb->replace( $wpdb->prefix.$_CONFIG['dbtable'], array( 'id' => 1, 'syncfields' => $syncfield), array('%d', '%s') );
$vtiger->logout($sessionId);
$vtiger->closeCurl();
$result = json_decode($result, true);
return var_dump(($result['success']) ? $result : "Error");
َAlso You Can Use vtiger CRM Webservice Client Library
http://forge.vtiger.com/projects/vtwsclib/

DynamoDB Update JSON

I have a dynamodb table that backs a shopping cart. The schema is CartKey then a List of Maps that contain a CartItemId. Is there a way to update a cart item, which is nested in the list of maps, based on the CartKey and a CartItemId.
Thanks
I'm in search for a solution to the same issue. Unfortunately I don't think one is available.
In mature document-based DBs (such as MongoDB) you should be able to specify a queried index (see https://docs.mongodb.org/manual/reference/operator/update/positional/#up.S), but DynamoDB doesn't support that.
The next best thing is to query the Cart document with the entire CartItems array, iterate it to find the index of your CartItem and do a conditional write. (For example: update the document and set CartItems[7].Quantity to 4 only if CartItems[7].ProductId is "WSK-1234")
Yes you need to do a read before a write and perform some client-side searching, but at least you can be sure you aren't updating the wrong item.
I would change your data model from a list of maps, to a map of maps where the keys are CartItemId's.
Example document:
{
CartKey : 'Cart-123',
items : : {
CartItemId1 : { quantity : 1, productId: "pid-123" },
CartItemId2 : { quantity : 4, productId: "pid-987" }
}
}
Then you can perform update expressions to specific CartItems.
UpdateExpression: "set items.CartItemId1.quantity = 2"
I did something similar with a map of maps and it worked for me. Hopefully this will be helpful.
$RegID = "abracadabra";
$tableName="DefaultDelivery";
$marshaler = new Marshaler();
$requested_delivery = '{"Packet0":{"PacketNo":"2","Quantity":"1000ml","Type":"Toned Milk"},"Packet2":{"PacketNo":"4","Quantity":"250ml","Type":"Toned Milk"}}';
$eav = $marshaler->marshalJson('
{
":RequestedDelivery" : '.$requested_delivery.'
}
');
$key = $marshaler->marshalJson('
{
"RegistrationID" : "'.$RegID.'"
}
');
$params = [
'TableName' => "$tableName",
'Key' => $key,
'ExpressionAttributeValues' => $eav,
'UpdateExpression' => 'SET RequestedDelivery = :RequestedDelivery',
'ReturnValues' => 'UPDATED_NEW'
];
try {
$result = $client->updateItem($params);
echo "SUCCESS";
}
catch (DynamoDbException $e){
echo "Unable to update Item : \n";
}

adding dropdown to joomla registration

I am want to add a dropdown to joomla 2.5 registration.I believe I can use sql form field type but I want that sql to return all schools of a particular city ( which is in registration form) .So question is how a sql query will accept a parameter?
You have to create one field type in the models==>fields.
for ex: create a php file as schools.php, and then include the following code.
==> schools.php(filename)
defined('JPATH_BASE') or die;
class JFormFieldSchools extends JFormField
{
protected $type = 'Schools';
protected function getInput()
{
// Initialize variables.
$html = array();
$attr = '';
// Initialize some field attributes.
$attr .= $this->element['class'] ? ' class="'.(string) $this->element['class'].'"' : '';
$attr .= ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : '';
$attr .= $this->element['size'] ? ' size="'.(int) $this->element['size'].'"' : '';
// Initialize JavaScript field attributes.
$attr .= $this->element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : '';
// Get some field values from the form.
$contactId = (int) $this->form->getValue('id');
$categoryId = (int) $this->form->getValue('catid');
// Build the query for the ordering list.
$query = 'SELECT ordering AS value, name AS text' .
' FROM #__contact_details' .
' WHERE catid = ' . (int) $categoryId .
' ORDER BY ordering';
// Create a read-only list (no name) with a hidden input to store the value.
if ((string) $this->element['readonly'] == 'true') {
$html[] = JHtml::_('list.ordering', '', $query, trim($attr), $this->value, $contactId ? 0 : 1);
$html[] = '<input type="hidden" name="'.$this->name.'" value="'.$this->value.'"/>';
}
// Create a regular list.
else {
$html[] = JHtml::_('list.ordering', $this->name, $query, trim($attr), $this->value, $contactId ? 0 : 1);
}
return implode($html);
}
}
Then you have to change the mysql query as your needs.
If have to change on the default joomla registration page then have following path(.../com_users/models/forms/registration.xml ).
<field name="xxxxx" type="Schools"
description="COM_USERS_REGISTER_NAME_DESC"
filter="string"
label="COM_USERS_REGISTER_NAME_LABEL"
message="COM_USERS_REGISTER_NAME_MESSAGE"
required="true"
size="30" />