it is possible to change the default received language from iso-3166-1-alpha-2 - reactjs

I would like to explain my problem of the day.
currently I receive data in the following format
[{location: "CU"},{location: "FR"},{location: "ES"}]
then I map and re map to correctly recover value, label, flag
const country = Array.from(
new Set(data?.map((e) => e.location))
).map((countryCode) => ({
value: countryCode,
label: `${iso3311a2.getCountry(countryCode)} (${countryCode})`,
flag: countryCode,
}));
it works correctly
I get the new data in the following format
[{flag: "CU" label: "Cuba (CU)"value: "CU"},
{flag: "FR" label: "France (FR) "value: "FR"},
{flag: "ES" label: "Spain (ES) "value: "ES"},
]
so my problem and the next one
here I recover spain
while I would like to recover "Espagne" according to the language
basically, is it possible to recover it in another language?
iam open to any proposal thank you very much.

Related

Discord.js v14: Embed-Fields empty after using EmbedBuilder

i have a strange Problem after updating from v13 to v14 that i don't understand.
A part of my Bot works as a Ticketsystem, where Tickets (as MessageEmbeds) can be changed via Reactions.
But when i try to change the embed with the new EmbedBuilder, every data inside the embed seems fine except the "fields"-data that are suddenly "undefined".
here is some example-code:
const embedObject = reaction.message.embeds[0]
console.log(embedObject.fields)
const tmpEmbed = EmbedBuilder.from(reaction.message.embeds[0])
console.log(tmpEmbed.fields)
First output is something like:
[
{ name: 'Priorität:', value: 'Normal', inline: true },
{ name: 'Übernommen:', value: '-', inline: true },
{ name: 'User:', value: '<#369058976245219330>', inline: false },
{ name: 'Inhalt:', value: '```test```', inline: false }
]
Second output is "undefined"
Solution:
With some trial and error i found a solution and possible inconsistency in the code of the discord-api (or it's my limit understanding) when trying to alter specific embed data.
So, what my code looked like in v13:
const embedObject = reaction.message.embeds[0]
embedObject.setDescription("**Status:** in Bearbeitung")
embedObject.setColor("#2db300")
embedObject.fields[1].value = `<#${user.id}>`
embedObject.setFooter({text: `Bearbeitet von: ${user.username}`, iconURL: userIcon})
embedObject.setTimestamp(new Date())
await reaction.message.edit({embeds: [embedObject]}).catch(console.error)
Now in v14, all of the .set-Functions didn't worked anymore for an already existing embed, so i thought i needed to construct an embed with the EmbedBuilder.
But now it's gets odd, while the .setDescription (and some other .set-Functions) just changed syntax to directly change the data (like it was for "fields" already):
const embedObject = reaction.message.embeds[0]
embedObject.Description = "**Status:** in Bearbeitung"
embedObject.fields[1].value = `<#${user.id}>`
for .setColor, .setFooter and .setTimestamp this doesn't work!
Also the "field"-data is not accessable from the EmbedBuilder-Object.
So you need to first edit some of the data "directly" (like description or fields) and then actually need to construct an embed with the EmbedBuilder to change color,footer and/or timestamp:
tmpEmbed = EmbedBuilder.from(embedObject)
.setColor(0x2db300)
.setFooter({text: `Bearbeitet von: ${user.username}`, iconURL: userIcon})
.setTimestamp(new Date())
Keep in mind, for this EmbedBuilder-Object, you can't read/change "fields", so do that before using the EmbedBuilder.
The working new code in v14, equal to the old code, is:
const embedObject = reaction.message.embeds[0]
embedObject.Description = "**Status:** in Bearbeitung"
embedObject.fields[1].value = `<#${user.id}>`
tmpEmbed = EmbedBuilder.from(embedObject)
.setColor(0x2db300)
.setFooter({text: `Bearbeitet von: ${user.username}`, iconURL: userIcon})
.setTimestamp(new Date())
await reaction.message.edit({embeds: [tmpEmbed]}).catch(console.error)
I'm no expert on Javascript or the Discord-API, so everything is learning by doing for me.
Possibly i got something wrong, did the v13 code already "odd" or am just missing something, but i hope this could help others when struggling with embeds :)

How do I select and update an object from a larger group of objects in Recoil?

My situation is the following:
I have an array of game objects stored as an atom, each game in the array is of the same type and structure.
I have another atom which allows me to store the id of a game in the array that has been "targeted".
I have a selector which I can use to get the targeted game object by searching the array for a match between the game ids and the targeted game id I have stored.
Elsewhere in the application the game is rendered as a DOM element and calculations are made which I want to use to update the data in the game object in the global state.
It's this last step that's throwing me off. Should my selector be writable so I can update the game object? How do I do this?
This is a rough outline of the code I have:
export const gamesAtom = atom<GameData[]>({
key: 'games',
default: [
{
id: 1,
name: 'Bingo',
difficulty: 'easy',
},
{
id: 21,
name: 'Yahtzee',
difficulty: 'moderate',
},
{
id: 3,
name: 'Twister',
difficulty: 'hard',
},
],
});
export const targetGameIdAtom = atom<number | null>({
key: 'targetGameId',
default: null,
});
export const targetGameSelector = selector<GameData | undefined>({
key: 'targetGame',
get: ({ get }) => {
return get(gamesAtom).find(
(game: GameData) => game.id === get(selectedGameIdAtom)
);
},
// This is where I'm getting tripped up. Is this the place to do this? What would I write in here?
set: ({ set, get }, newValue) => {},
});
// Elsewhere in the application the data for the targetGame is pulled down and new values are provided for it. For example, perhaps I want to change the difficulty of Twister to "extreme" by sending up the newValue of {...targetGame, difficulty: 'extreme'}
Any help or being pointed in the right direction will be appreciated. Thanks!

react-semantic-redux-form selectField multiple

I am attempting to use react-semantic-redux-form SelectField with the multiple options so a user can select multiple options and if there is one already set then this should show as checked.
I am also using redux-form with semantic0ui-react.
I am getting an error attempting to include multiple selections.
My include statement is:
import { SelectField } from "react-semantic-redux-form";
My state is:
state = {
relationships: ["some entry"],
relationshipOptions: [],
};
The element code is:
<Grid.Column>
<Field
component={SelectField}
name="relationships"
label="Your Relationships"
options={relationshipOptions}
multiple
placeholder="Select to add a relationship"
/>
I get the error as below
Dropdown `value` must be an array when `multiple` is set. Received type: `[object String]`.
in Dropdown
The way you have relationshipOptions is wrong, it is supposed array of objects,
const relationshipOptions = [
{ key: "single", value: "single", text: "single" },
{ key: "married", value: "married", text: "married" }
];
Here is the working example, Code Sandbox
Also if you have single, married in array. You can do something like this,
let relationshipOptions = ["single", "married"].map((x) => {
return ({
key: x,
value: x,
text: x
});
});

How to set value for additional column in pivot table in OctoberCMS?

I have doctor and specialization table, and have doctor_specialization_pivot table. In my pivot table I have the following columns:
| doctor_id | additional_data | specialization_id |
additional_data is from the doctor model along with the doctor_id.
In my doctor model file, I have this relationship:
public $belongsToMany = [
'specialization' => [
'path\to\specialization\model',
'table' => 'doctor_specialization_pivot',
'parentKey' => 'doctor_id',
'otherKey' => 'specialization_id',
]
];
Now during submit of form, I'm getting this error:
SQLSTATE[HY000]: General error: 1364 Field 'additional_data' doesn't have a default value (SQL: insert into doctor_specialization_pivot (doctor_id, specializations_id) values (1, 3))"
I tried adding to my relationship 'pivot' => ['additional_data']. But still getting the same error.
I checked the submitted data and additional_data is not empty. I checked from OctoberCMS forums but not getting straight forward answers such as this and this.
Okay. I found the answer to my own question.
I'll answer in detail to help everyone. After digging and blind shooting. According to this documentation here, we can use the method attach() to attach a role to a user by inserting a record in the intermediate table that joins the models.
What confuse me in the documentation is that it uses a $roleId variable and I didn't understand where the $roleId came from. If it's the id of the parent table or the id of other table.
Sample from the link:
$user = User::find(1);
$user->roles()->attach($roleId);
So what I did in my doctor model, I hook to the event beforeSave, use the relationship ($this->specialization) as the first parameter instead of the id in the docs. The $this->specialization() is the relationship too defined in belongsToMany.
Answer:
public function beforeSave()
{
$this->specialization()->attach($this->specialization,['additional_data' => 'additional data from doctor table']);
}
The implementation is pretty much like this video from Watch Learn (Ivan). You can learn a lot about OctoberCMS just by watching his guide on it. Here is the documentation on it as well. This is the example info that I have done.
WARNING Another known flaw is you can't apply this to a model record that isn't created yet. Unlike the standard relation widget which waits until it is saved before attaching records this attaches records in a separate overlay form.
Here is my model.php relationship:
public $belongsToMany = [
'equipments' => [
'Brandon\Pixelrpg\Models\Equipments',
'table' => 'brandon_pixelrpg_equipment_inventory',
'key' => 'inventory',
'otherKey' => 'equipment',
'pivot' => ['quantity']
]
];
Here is my controller.php:
public $implement = [
'Backend\Behaviors\ListController',
'Backend\Behaviors\FormController',
'Backend\Behaviors\ReorderController',
'Backend\Behaviors\RelationController'
];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $reorderConfig = 'config_reorder.yaml';
public $relationConfig = 'config_relation.yaml';
Here is my config_relation.yaml:
equipments:
label: Equipments
view:
list:
columns:
id:
label: ID
type: number
searchable: true
sortable: true
name:
label: Name
type: text
searchable: true
sortable: true
value:
label: Value
type: number
searchable: true
sortable: true
updated_at:
label: Updated
type: datetime
searchable: true
sortable: true
pivot[quantity]:
label: Quantity
type: number
pivot:
form:
fields:
pivot[quantity]:
label: Quantity
type: number
default: 0
I am just going to make a new answer and assume is what you need because you have yet to show any code on how your form works. This is how I would update the pivot information from a frontend form.
Relationship in model.php:
public $belongsToMany = [
'specialization' => [
'path\to\specialization\model',
'table' => 'doctor_specialization_pivot',
'parentKey' => 'doctor_id',
'otherKey' => 'specialization_id',
'pivot' => ['additional_data'] //This is required
]
];
Then in some php code lets call it onAddSpecialization():
public function onAddSpecialization() {
//Calling a function to get the doctor id maybe from the signed in user
$doctor = Doctors::find($this->$doctorId());
//We get our Specialization from an input
$specialization = Specialization::find(Input::get('specialization_id'));
//We get our additional data from an input
$additional_data = Input::get('additional_data');
//Now we are going to attach the information
$doctor->specialization()->attach($specialization, ['additional_data' => $additional_data]);
}
Now an example of updating our additional data:
public function onUpdateAdditionalData() {
//Calling a function to get the doctor id maybe from the signed in user
$doctor = Doctors::find($this->$doctorId());
//If you get specialization by id from an input. I believe you need to go through the relationship in order to access the correct pivot information.
$specialization = $doctor->specialization->where('id', Input::get('specialization_id'))->first();
//Insert the new pivot information
$specialization->pivot->additional_data = $new_additional_data;
//Save
$specialization->pivot->save();
}

Ng-admin: How to show different fields according to user's selection?

I am using ng-admin to write a admin management. I met below issue, can somebody help me?
In my creationView, I would like to show different fields(text/video/pictures) according to the selection of "type" field. How I can make it?
var articles = nga.entity('articles');
articles.creationView().fields([
nga.field('type','choice')
.validation({ required: true })
.choices([
// 1: txt, 2: pic, 3: vid
{ value: 1, label: 'Text'},
{ value: 2, label: 'Picture'},
{ value: 3, label: 'Video'},
]),
nga.field('txt','file')
.attributes({ placeholder: 'Write something... !' }),
nga.field('pic','file')
.label('Picture(.jpg|.png)')
.uploadInformation({ 'url': '/api/adminapi/uploadPicture', 'apifilename': 'pictures', 'accept': 'image/jpg,image/png'}),
nga.field('vid','file')
.label('Video(.mp4)')
.uploadInformation({ 'url': '/api/adminapi/uploadVideo', 'apifilename': 'video', 'accept': 'video/mp4'}),
])
The Field Configuration doc page explains how to do this using the "template" field config:
template(String|Function, templateIncludesLabel=false) All field types
support the template() method, which makes it easy to customize the
look and feel of a particular field, without sacrificing the native
features.
...
To force the template to replace the
entire line (including the label), pass true as second argument to the
template() call. This can be very useful to conditionally hide a field
according to a property of the entry:
post.editionView()
.fields([
nga.field('category', 'choice')
.choices([
{ label: 'Tech', value: 'tech' },
{ label: 'Lifestyle', value: 'lifestyle' }
]),
nga.field('subcategory', 'choice')
.choices(function(entry) {
return subCategories.filter(function (c) {
return c.category === entry.values.category;
});
})
// display subcategory only if there is a category
.template('<ma-field ng-if="entry.values.category" field="::field" value="entry.values[field.name()]" entry="entry"
entity="::entity" form="formController.form"
datastore="::formController.dataStore"></ma-field>', true),
]);
I just have a work round method. That is using .attributes(onclick, "return updateButton();") for nga.field("type"). In updateButton() method, it will help to check current 'type' field value and using DOM methods to change the button enable and disabled.
However, I still realy appreciate that if this requirement can be support in future. It will be helpful for user to make UI controls easily.

Resources