Displaying database columns based on current language - laravel

in database i have this:
name_en | name_fr
When the user select french language - for example - i want to get name_fr field, and the same thing if he chose another language

Assuming you set locale in your application using:
App::setLocale($lang);
if you use Eloquent, you can add to your model class accesssor:
public function getNameAttribute($value) {
return $this->{'name_'.App::getLocale()};
}
and also mutator:
public function setNameAttribute($value) {
$this->{'name_'.App::getLocale()} = $value;
}
Assuming you added those functions to Content model you can now use:
$content = Content::first(); // find first article
echo $content->name; // displaying its name
$content->name = 'updated content'; // changing its name
$content->save(); // saving
This will cause displaying and changing name_{$lang} if you set lang using setLocale

Related

Backpack V4 modifying field before store

In 3.6 version of backpack I can change an attribute value before storing it.
I have this code
If ($request->description == "") {
$request->description="User has not entered any description";
}
$redirect_location = parent::storeCrud($request);
What can I do to get the same in V4? I'm reading this guide but I can't make it to work.
This is what I'm trying in V4
public function store(PedidoRequest $request)
{
Log::debug('testing...');
If ($request->description == "") {
$request->description="User has not entered any description";
}
$redirect_location = $this->traitStore();
return $redirect_location;
}
The Request object in Laravel, Illuminate\Http\Request, doesn't have the ability to set the inputs via the properties like that, no __set method ($request->description = '...' does not set an input named description). You would have to merge the inputs into the request or use the array syntax to do that:
$request->merge(['description' => '...']);
// or
$request['description'] = '...';
But since backpack seems to have abstracted things apparently you aren't controlling anything in your controller methods you could try this:
$this->crud->request->request->add(['description'=> '...']);
Potentially:
$this->request->merge(['description' => '...']);
That would be assuming some trait the Controller uses is using the Fields trait.

Magento 2.3 graphql get custom attribute option values

I’m pretty frustrated with the graphql api of Magento. How is it not possible to receive the values of a custom attribute. I mean it’s easy to make a custom select-option attribute and making it available through graphql but you are only getting the integer value.
What’s the best procedure to following
1. Query the complete attribute to get the value
2. Extending the graphql schema (this involves a developer every time the client changes something)
3. Am I missing some functionality inside the graphql endpoints to Fix this?
From Native GraqpQl we cannot get the expected result.But we can write a custom module with the graphql and achieve it.What my suggestion is get the product detail by sku using _productRepository->get($sku);. This will return the entire product details.So you can get the attribute data by using $attributes = $_product->getAttributes(); Here is my data provider file.
/**
* #params string $sku
* this function return all the product data by product sku
**/
public function getProductBySku($sku)
{
return $this->_productRepository->get($sku);
}
/**
* #params int $id
* this function return all the word of the day by id
**/
public function getAttributesBySku( $sku ){
$_product = $this->getProductBySku($sku);
$attributes = $_product->getAttributes();// All Product Attributes
$attributes_data = [];
$x=0;
foreach ($attributes as $attribute) {
if($attribute->getIsUserDefined()){ // Removed the system product attribute by checking the current attribute is user created
$attributeLabel = $attribute->getFrontend()->getLabel();
$attributeValue = $attribute->getFrontend()->getValue($_product);
if($attribute->getAttributeCode()=="language"){
$attributeLabelAndValue = $attributeLabel." - ".$attributeValue;
$attributes_data[$x]['atr_data'] = $attributeLabelAndValue;
}
}
$x++;
}
return $attributes_data;
}
This code will return the need
$attribute->getFrontend()->getLabel(); this will return the label and
$attribute->getFrontend()->getValue($_product); this will return the value.
To check the entire graphQl query and resolver file kindly view How to get product attribute value, label using GraphQl in Magento 2.3?
Hope this will help you.
You can try creating custom graphql attribute with custom resolver.
$product = $this->_productRepository->getById($value['entity_id']);
$data = array();
foreach ($args['fields'] as $fi) {
$att = $product->getResource()->getAttribute($fi);
if (isset($att) && $att) {
if (in_array(
$att->getFrontendInput(),
['multiselect', 'select']
)) {
$data[$fi . '_label'] = $product->getAttributeText($fi);
}
$data[$fi] = $product->getData($fi);
}
}
return json_encode((object) $data);
which should display all provided attributes with their labels.
"sku": "testProduct",
"fabric": 60,
"work": 65,
"dynamicAttributes": "{
"fabric_label":"Pure Silk",
"fabric":"60",
"work_label":"Tanchoi",
"work":"65"
}",
Check out entire module here

How to stop slug generation in OctoberCMS

When I write non-unicode letters in OctoberCMS Rainlab blog title, it's converted to English letters such as this:
موضوع جديد
is converted to: modoaa-gdyd
I don't want this, I want only to replace spaces with hyphen to be for example:
موضوع-جديد
How can I do that?
Hmm for now it seems we are not able to extend js plugin for give purpose
but we can extend plugin to not use slug type
you can add this code to any of your plugin's boot method
boot method is imp
<?php namespace HardikSatasiya\DemoTest;
use System\Classes\PluginBase;
class Plugin extends PluginBase
{
public function registerComponents()
{
}
public function registerSettings()
{
}
public function boot() {
\Event::listen('backend.form.extendFieldsBefore', function($widget) {
// You should always check to see if you're extending correct model
if(!$widget->model instanceof \RainLab\Blog\Models\Post) {
return;
}
// now we remove type = slug , and use exact
// as type = slug will convert chars ARABIC_MAP to english so
$widget->fields['slug']['preset']['type'] = 'exact';
});
}
}
It will not solve your complete problem but it can simply copy your blog-title exactly in to slug, in slug text-box then you need to add / at the beginning and then you also need to place ' ' => '-' (dash at spaces) manually.
sorry this will not solve your whole issue, but just saves you from copying title to slug again and again.
Add this function as a helper in your app and reuse it
public static function generateSlug($title)
{
$title = strtolower($title);
$title = preg_replace("/[\s-]+/", ' ', $title);
$title = preg_replace("/[\s_]/", '-', $title);
return $title;
}
$slug = Helpers::generateSlug('موضوع جدید', '-');
//will produce "موضوع-جدید"
Or use this package
Sluggable Persian
I solved this problem by editing the following file:
modules\system\assets\ui\storm-min.js
I emptied the following variables:
ARABIC_MAP={},PERSIAN_MAP={}
and edited the slugify function by replacing this line:
slug=slug.replace(/[^-\w\s]/g,'')
with this:
slug=slug.replace(/[^-\w\sء-ي]/g,'')
so, now the slug accepts Arabic characters normally

Translate controller class variables in zend framework 2

Let's say I have a controller and I want to define some const variables that hold some messages (eg error messages etc).
Is there a way to make it so they are translated?
An example class is defined bellow:
<?php
namespace Test\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AccountController extends AbstractActionController
{
protected $testError = 'There was an error while testing some stuff';
public function testAction(){
// I know i can use the following approach but I don't want to
// since I want to use a variable for readability issues.
// $testError = $this->getTranslator()->translate('There was an error..');
return new ViewModel();
}
/**
* Retrieve the translator
*
* #return \Zend\I18n\Translator\Translator
*/
public function getTranslator()
{
if (!$this->translator) {
$this->setTranslator($this->getServiceLocator()->get('translator'));
}
return $this->translator;
}
/**
* Set the translator
*
* #param $translator
*/
public function setTranslator($translator)
{
$this->translator = $translator;
}
}
So I want to have the testError translated. I know I can just use the message and translate it via the zend translator without using a variable, but still I want to store it in a variable for readability issues. Any help or other approaches to this?
Simply create a translations.phtml file in any directory in your project root and fill it something like that:
<?php
// Colors
_('Black');
_('White');
_('Green');
_('Light Green');
_('Blue');
_('Orange');
_('Red');
_('Pink');
In poedit, check Catalog Properties > Source keywords list an be sure _ character is exists. (Alias of the gettext method). In application, use $this->translate($colorName) for example.
When poedit scanning your project directory to find the keywords which needs to be translated, translations.phtml file will be scanned too.
Another handy approach is using _ method (gettext alias) to improve code readability. Example:
$this->errorMsg = _('There was an error..');
But don't forget to set the global Locale object's default locale value too when you initialising your translator instance first time in a TranslatorServiceFactory or onBootstrap method of the module:
...
$translator = \Zend\Mvc\I18n\Translator\Translator::factory($config['translator']);
$locale = 'en_US';
$translator->setLocale($locale);
\Locale::setDefault($translator->getLocale());
return $translator;
...
I don't quite understand what you mean:
$errorMessage = 'FooBarBazBat";
return new ViewModel(array(
'error' => $this->getTranslator()->translate($errorMessage)
));
would be a way to store the message inside a variable. But i really don't understand where your problem is.
Or do you mean having the translator as variable?
$translator = $this->getServiceLocator()->get('viewhelpermanager')->get('translate');
$errorMessage = $translator('FooBarBazBat');

Set dropdown input default value based on third parameter in Grocery CRUD

Code sample below,
function product($parameter){
$crud = new grocery_CRUD();
...
$crud->callback_add_field('dropdown_field_name',array($this,'_add_field_callback'));
...
$output = $crud->render();
}
Can I do something like this ?
function _add_field_callback($parameter){
//load db model
//call the result and return as dropdown input field with selected selection when value = $parameter
}
Actually this is easy to do it by using the controller. For example you can simply do:
function product($parameter){
$this->my_test_parameter = $parameter;
$crud = new grocery_CRUD();
...
$crud->callback_add_field('dropdown_field_name',array($this,'_add_field_callback'));
...
$output = $crud->render();
}
And the callback:
function _add_field_callback($parameter){
//load db model
//call the result and return as dropdown input field with selected selection when value = $parameter
$value = !empty($this->my_test_parameter) ? $this->my_test_parameter : '';
...
//here you can also use the form_dropdown of codeigniter (http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html)
}
I know that you are desperately looking forward for the default value for grocery CRUD so I added an issue to the github https://github.com/scoumbourdis/grocery-crud/issues/138 . This is will be a reminder that this thing has to be fixed.
I had implemented Grocery Crud in one of my web application.
Check this link on " How to create dependent dropdowns"
http://demo.edynamics.co.za/grocery_crud/index.php/examples/customers_management/add

Resources