$status=1 or 0 then display Enable or disable respected how can translate in yii2 MVC - yii2-advanced-app

My database column "status" stores "0 or 1" value but I want to display "Enable" or "disable"

Try this... This might be helpful to you.
Modify code as per your need.
[
'attribute' => 'status',
'value' => function ($model, $key, $index, $widget) {
if ($model->status == 0) {
$status = 'disable';
} elseif ($model->status == 1) {
$status = 'Enable';
} else {
$status = 'Completed';
}
return $status;
}
]

Related

Magento 2 - Update Product stock and Price Programmatically for multiple stores

I'm getting data from the CSV file and according to SKU file load the product.
We are getting 30 products from the CSV file and update those product data in Magento.
We have set up cron every 5 minutes and after 5 minutes it will get the next 30 products and update.
The starting process script is working fine. But after the sometime script is going to be slow and it will take time to update the product.
So, the next cron is running at on the same time there are lots of scripts are running on the server, and the server load will increase.
After taking so much load on the server website going to be slow.
Can you please let me know the way so product updating process will be consistent and time will not so much vary.
public function execute()
{
$data = array of csv file data;
$sql = "Select value FROM " . $tableName . " where path='catalog/product/update_cron' and scope_id=0";
$result = $connection->fetchAll($sql);
$update_cron = $result[0]['value'];
$total_products = count($data);
if ($total_products == $update_cron) {
$this->configWriter->save('catalog/product/update_cron_status', '1', 'default', '0'); // inject Magento\Store\Model\ScopeInterface;
exit;
}
if ($update_cron != '' && $update_cron != 0) {
$data = array_slice($data, (int)$update_cron, 30);
} else {
$update_cron = 0;
$data = array_slice($data, 0, 30);
}
$current_date = date("m/d/Y");
$i = 0;
foreach ($data as $key => $value) {
/*********************************************Update Product Price********************************************************/
if ($value['Artikel'] != '') {
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product_id = $product->getIdBySku($value['Artikel']);
if (!empty($product_id)) {
/************************Update Product Price for all Stores**************************************/
$price_b2b = str_replace(',', '.', (string) $value['Verkoopprijs']);
$price_b2c = str_replace(',', '.', (string) $value['Numeriek1']);
$price_club = str_replace(',', '.', (string) $value['Numeriek2']);
//$special_price_b2b = str_replace(',', '.', (string) $value['Numeriek3']);
$productActionObject = $objectManager->create('Magento\Catalog\Model\Product\Action');
$productActionObject->updateAttributes(array($product_id),
array(
'name' => $value['Artikel'],
'ean_code'=>$value['Barcode'],
'price'=>$price_b2c,
'price_wholesale'=>$price_b2b,
'price_clubs'=>$price_club,
'description'=>$value['Omschrijving Engels'],
),0
);
/* if ($value['Boolean1'] == 'True') {
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => $special_price_b2b, 'special_from_date' => $current_date), 4);
} else { */
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => '', 'special_from_date' => ''), 4);
//}
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_club), 7);
/*********************************************Inventory Update********************************************************/
$stockRegistry = $objectManager->create('Magento\CatalogInventory\Api\StockRegistryInterface');
$sku = $value['Artikel'];
if($sku != '')
{
$qty = round(str_replace(',', '', (string) $value['Stock']));
$stockItem = $stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($value['Stock']);
$stockItem->setIsInStock((int) ($qty > 0)); // this line
$stockRegistry->updateStockItemBySku($sku, $stockItem);
}
/*****************************************************************************************************/
}
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
else {
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
}
die('records completed');
}
}
die('stop');
}
Thanks in advance

Laravel-mongo DB

I'm using https://github.com/jenssegers/laravel-mongodb
$query = $this->proposal->where('status', 'approved')
->with(['evaluations', 'user', 'contributions'])
->with(['reviews' => function ($q) {
$q->where('status','approved')->orderBy('created_at', 'desc');
}]);
if( .... ) {
dd($query->toSql()); // "select * from "proposals" where "status" = ?"
$proposalsFoundByTile = $query->where('title','like',"%$request->search%")->get();
dd($query->toSql()); // "select from "proposals" where "status" = ? and "title" like ?"
...
}
Why $query value changed? How can I "clear" this changes to initial value?
After this line,
$proposalsFoundByTile = $query->where('title','like',"%$request->search%")->get();
put this,
$key = array_search("title", array_column($query->getQuery()->wheres,
'column'));
unset($query->getQuery()->wheres[$key]);
Then this will return,
dd($query->toSql()); // "select from "proposals" where "status" = ?"
As adviced in comments solved this problem with clone() function.
$query = $this->proposal->where('status', 'approved')
->with(['evaluations', 'user', 'contributions'])
->with(['reviews' => function ($q) {
$q->where('status','approved')->orderBy('created_at', 'desc');
}]);
if( .... ) {
$subQuery = clone($query);
$proposalsFoundByTile = $subQuery->where('title','like',"%$request->search%")->get();
...
$subQuery = clone($query);
$some_var = $subQuery->... ;
}

Getting a menu delivered via REST

I am trying to get a menu via REST and I've created a new module and rest resource plugin that allows for GET on /entity/restmenu/{menu_name}.
I can successfully return this example json using this function when I hit the URL.
public function get(EntityInterface $entity) {
$result = array();
for ($i = 0; $i < 10; $i++) {
$temp = array(
'title' => 'Test ' . $i,
'href' => '#/' . $i
);
array_push($result, $temp);
}
return new ResourceResponse(json_encode($result));
}
I cannot figure out how to load the menu based on $entity. If I hit my URL (http://dang.dev:8888/entity/restmenu/main?_format=hal_json) $entity's value is 'main' which is the machine name of the main menu.
I've tried using Drupal menu tree, but I am not having luck, and debugging this thing with only JSON responses is quite difficult.
How do I get menu item titles and paths based on the menu machine name?
EDIT
Ok, sort of figured it out.
public function get($entity) {
$menu_name = $entity;
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$renderable = \Drupal::menuTree()->build($tree);
$result = array();
foreach (end($renderable) as $key => $val) {
$temp = array(
'menu_item' => $val,
'route' => $key
);
array_push($result, $temp);
}
return new ResourceResponse(json_encode($result));
}
Right now that will output:
[
{
"menu_item":{
"is_expanded":false,
"is_collapsed":false,
"in_active_trail":false,
"attributes":"",
"title":"Home",
"url":{
},
"below":[
],
"original_link":{
}
},
"route":"standard.front_page"
},
{
"menu_item":{
"is_expanded":false,
"is_collapsed":false,
"in_active_trail":false,
"attributes":"",
"title":"Communities",
"url":{
},
"below":[
],
"original_link":{
}
},
"route":"menu_link_content:139d0413-dc50-4772-8200-bc6c92571fa7"
}
]
any idea why url or original_link are empty?
This was the correct answer:
public function get($entity) {
$menu_name = $entity;
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$result = array();
foreach ($tree as $element) {
$link = $element->link;
array_push($result, array(
'title' => $link->getTitle(),
'url' => $link->getUrlObject()->getInternalPath(),
'weight' => $link->getWeight()
)
);
}
return new ResourceResponse(json_encode($result));
}

PHP preg_replace_callback replace wrong open and end tags

I'm having a problem with my BB-Code function. I've tested followig input to replace:
Testtext! <b>text<u>testtext</u>test</b><b>test</b>
and get this (mixed) output:
Testtext! [b]text[u]testtext[/u]test</b>test<b>test[/b]
my PHP-Code:
function html_to_bbcode($input) {
$regex[] = '#\<b>((?:[^[]|\<(?!/?b>)|(?R))+)\</b>#im';
$regex[] = '#\<i>((?:[^[]|\<(?!/?i>)|(?R))+)\</i>#im';
$regex[] = '#\<u>((?:[^[]|\<(?!/?u>)|(?R))+)\</u>#im';
if (is_array($input)) {
$tag = explode('>', $input[0]);
$tag = str_replace('<', '', $tag[0]);
if ($tag == 'b') {
$input = '[b]'.$input[1].'[/b]';
} else if ($tag == 'i') {
$input = '[i]'.$input[1].'[/i]';
} else if ($tag == 'u') {
$input = '[u]'.$input[1].'[/u]';
}
}
return preg_replace_callback($regex, 'html_to_bbcode', $input);
}
(and some more Tags)
I can't find that bug :( Have anyone an solution for this?

Laravel selectRange blank option

I am creating a "day" select dropdown. With a selectRange I can do this:
{{ Form::selectRange('day', 1, 31, $day) }}
The problem is, when the form loads, if $day is not set it selects 1 by default. Is it possible to use selectRange to give them a "Please Choose" option that has a NULL value?
Use Form::select instead.
{{ Form::select('day', array('' => 'Please Choose...') + range(1,31)) }}
Use Form Select with range and array_combine if you want to modify the option value:
{{ Form::select('month', array('all' => 'all') + array_combine(range(1,12),range(1,12)) ) }}
I don't believe there is a way of achieving this with the built in selectRange, however it is possible using form macros. The following macro performs roughly what you're looking for, though may require some cleanup.
Form::macro('selectRangeWithDefault', function($name, $start, $end, $selected = null, $default = null, $attributes = [])
{
if ($default === null) {
return Form::selectRange($name, $start, $end, $selected, $attributes);
}
$items = [];
if (!in_array($default, $items)) {
$items['NULL'] = $default;
}
if($start > $end) {
$interval = -1;
$startValue = $end;
$endValue = $start;
} else {
$interval = 1;
$startValue = $start;
$endValue = $end;
}
for ($i=$startValue; $i<$endValue; $i+=$interval) {
$items[$i . ""] = $i;
}
$items[$endValue] = $endValue;
return Form::select($name, $items, isset($selected) ? $selected : $default, $attributes);
});
Usage is as follows:
{{ Form::selectRangeWithDefault('day', 1, 31, $day, 'Please Choose...') }}
Note that I got the idea and the basis for my code from: https://stackoverflow.com/a/25069699/3492098
this one works with reverse list :
Form::macro('selectRangeWithDefault', function($name, $begin, $end, $selected = null, $default = null, $attributes = [])
{
if (!is_array($default) || $default === null) {
return Form::selectRange($name, $begin, $end, $selected, $attributes);
}
$range = $default + array_combine($range = range($begin, $end), $range);
return Form::select($name, $range, $selected, $attributes);
});
Exemple :
{!! Form::selectRangeWithDefault('year', date('Y'), 1915, $user->getBirthYear(), ['' => 'YYYY']) !!}
And if you are looking how to add a macro : Where to put HTML macros in laravel 5?
Use Form::select instead of Form::selectRange
Also, according to the best practices you can use the placeholder parameter in order to create a blank option.
{{ Form::select('day', range(1, 31), null, ['placeholder' => '']) }}
use placeholder
{{ Form::selectRange('day', 1, 31, $day,['class' => 'form-control input-lg','id'=>'day','placeholder' => 'Please Choose']) }}