React-Admin Change values to custom values in the SelectInput - react-admin

I have the following code that I'm using in react-admin:
<ReferenceInput label="Animal" source="id"reference="animal">
<SelectInput optionText="type" choices={[ {id: '0', name: 'Cat' }, { id: '1', name: 'Dog'},]}/>
</ReferenceInput>
In that code it receive from my database the values '0' to a Cat and '1' to a dog and when I click in the dropDown it's show '0' and '1', but I want to show only Cat and Dog instead of '0' and '1' in my SelectInput.
I tried to use: choices={[ {id: '0', name: 'Cat' }, { id: '1', name: 'Dog'},]}, but had no effect in the dropdown.
Does anyone know how I can do this?

You can pass in the optionText prop your function of displaying the selected record instead of the string with the field name:
<ReferenceInput label="Animal" source="id" reference="animal">
<SelectInput optionText={ choice => choice.type === 0 ? 'Cat' : 'Dog' }/>
</ReferenceInput>

I found out what my problem was.
The value coming from the database was just a numeric value (0, 1) and I was using ('0', '1'). And the SelectInput could not use the correct value to display in DropDown because of that.
The right way should be like this:
<SelectInput
optionText = "type"
choices = {[{id: 0, name: 'Cat'}, {id: 1, name: 'Dog'},]}
/>
Where numeric values do not use quotation.

Related

PostgreSQL / TypeORM: String array type, how to use LIKE in query?

My backend database is PostgreSQL
I have a TypeORM object simplified to:
#Entity()
#Index(['name'], {unique: true}
export class Foo extends BaseEntity
{
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
#Column('varchar', { array: true })
bar: string[];
}
I'm creating an API query handler that can handle searches. I can easily do a LIKE query on the name like this:
let qs = Foo.createQueryBuilder('foo');
qs.andWhere('foo.name ILIKE :name', {
name:'%${name}%'
});
I'd like to also search for e.g. any "bar" LIKE %myqueryterm% but I can't seem to find anything on that.
I see a bunch of docs on how to exactly match a search term in bar, but no soft comparison.
What I essentially want to do is that I have a data set
[
{id: 1, name: 'whatever', bar: ['apple','bananna','yeti','woo']},
{id: 2, name: 'something else', bar: ['red','blue','green', 'boo']},
{id: 3, name: 'i dunno', bar: ['ford','chevy']},
]
and I'd like to let the user to be able to query e.g. "%oo% and return the first 2 records based on bar strings containing that substring.
Postgres provides array functions and operators that you can use to create any complex query.
In your case, a clean way of doing this would be to
Convert the array to a string and then
Perform the LIKE operation on that string
Something like this should work:
.createQueryBuilder('foo')
.where("array_to_string(foo.bar, ',') LIKE :bar", {
bar: '%aa%',
})
.getMany();
I don't know typeorm. but based on https://github.com/typeorm/typeorm/issues/881
The sql query would be like:
WITH cte (
id,
name,
bar
) AS (
VALUES (1, 'whatever', ARRAY['apple', 'bananna', 'yeti', 'woo']),
(2, 'something else', ARRAY['red', 'blue', 'green', 'boo']),
(3, 'i dunno', ARRAY['ford', 'chevy'])
),
cte1 AS (
SELECT
json_agg(row_to_json(cte.*)) AS json_all
FROM
cte
)
SELECT
value
FROM
cte1,
json_array_elements(json_all)
WHERE
value ->> 'bar' ~ 'oo';
Based on the github page, it would be like:
getConnection().query("
with cte(id,name,bar) as (values
(1,'whatever',array ['apple','bananna','yeti','woo'])
,(2,'something else',array ['red','blue','green', 'boo'])
,(3,'i dunno',array ['ford','chevy'])
),cte1 AS
(select json_agg(row_to_json(cte.*)) as json_all from cte)
select value
from cte1,json_array_elements(json_all)
where value->>'bar' ~ #0", ['oo']);
case insensitively match would be value->>'bar' ~* #0"

React native how to update multiple state values

Here is the user details which I want to update values when user enters data in Textinput
const [details, setDetails] = React.useState({
isValidName: true,
isValidMobile: true,
isValidEmail: true,
isValidGSTIN: true,
isValidPAN: true,
name: '',
mobile: '',
email: '',
company: '',
baddr1: '',
baddr12: '',
bcity: '',
bpincode: '',
bstate: ' TAMIL NADU',
bcountry: 'INDIA',
saddr1: '',
saddr2: '',
sbranch: '',
sgstin: '',
scity: '',
spincode: '',
sstate: '',
scountry: '',
pan: '',
gstin: '',
userlevel: '',
});
//In this method i am updating values each time when user enters data
const submitBillAddress = (data, type) => {
console.log('bill', type);
switch(type){
case 'addr1':
setDetails((prevState)=>{
return({
...prevState,
baddr1: data
});
});
break;
}
console.log('billdetails', details);
};
return (
<View>
<TextInput
style={styles.TextInputStyleClass}
placeholder="Address Line 1"
value={sameAddress?null:details.baddr1}
onChangeText={val => submitBillAddress(val, 'addr1')}
/>
</View>
)
I am new to React Native application development and I know this question is basic but I am not getting exact output. Here I have one Textinput in which I am entering data that I wanted to store in details.
The issue is if I enter data in textinput it's not updating value in details. Let's say I am entering 'C' in Textinput if I try to check the value in console the value of details.baddr1='' it's empty, Second time if I enter value 'H' on that time in console the value of details.baddr1='C'. Instead of showing the value details.baddr1='CH' it's showing previously entered value.
How can I fix this issue?
I'm guessing this is for a form of some sort. In that case, a package is your best bet I believe. While what you're trying to achieve is possible without a package, using a package is far less painful in the long run for your app.
Please check out formik or react-hook-form.
They're both decent.

Filter Vue list based on select option value

I try to filter my list with 2 select lists based on the selected value. It seems like my computed filter is not working?
You should be able to filter the list on 'Price from' and 'Price to'
List.vue
My computed filter property:
filteredData() {
const LowerCaseSearch = this.search.toLowerCase();
return this.products.filter(
product =>
(product.name.toLowerCase().includes(LowerCaseSearch) ||
product.category.toLowerCase().includes(LowerCaseSearch)) &&
(!this.checked.length || this.checked.includes(product.category)) &&
(!this.selectedFrom.length || this.selectedFrom.includes(product.price)) &&
(!this.selectedTo.length || this.selectedTo.includes(product.price))
);
},
In my registered component I use v-model to bind to the computed property selectedFrom
<Price v-model="selectedFrom" />
How do I bind to the other property selectedTo in one v-model and what's wrong with my filter?
I also use a prefix 'From' and 'To' to put in front of the options.
data: () => {
return {
selectedFrom: '0,00',
priceFrom: [
{ prefix: 'From', text: '0,00', value: '0,00' },
{ prefix: 'From', text: '200,00', value: '200,00' },
{ prefix: 'From', text: '400,00', value: '400,00' }
],
selectedTo: 'No max',
priceTo: [
{ prefix: 'To', text: '400,00', value: '400,00' },
{ prefix: 'To', text: '600,00', value: '600,00' },
{ prefix: 'To', text: '800,00', value: '800,00' },
{ text: 'No max', value: 'No max' }
]
}
},
Is there a more elegant and D.R.Y way to do this?
Here is a sandbox what I have so far.
You should bind an object to your v-model on the <price> component.
This way you can pass multiple values to and from your component, without having to use multiple props.
I would also suggest you convert your value in your selects to numbers, so it's easier to use them to compare to your prices.
You've also defined data properties and computed properties in the sandbox (<price> component) with the same name, this is not possible. So you should remove the data properties and stick to the computed ones to handle your data.
Fork of your sandbox with my suggested changes.

How to set defaultValue for multi select?

So, I need to pass defaultValue to a react-select component with enabled multi select. I've tried everything I could think of: array of strings, array of objects, string, etc... Nothing seems to work.
I'm also using the getOptionLabel and getOptionValue, might they be the cause for all this mess?
If you refer to react-select documentation, the way to set defaultValue to multiple value select:
<Select
defaultValue={[colourOptions[2], colourOptions[3]]}
isMulti
name="colors"
options={colourOptions}
className="basic-multi-select"
classNamePrefix="select"
/>
The structure of options is
[
{
label: <string>,
value: <string>,
}
]
Working example here.
There is an alternate way to use value as your defaultValue.
In my case I have used "id" and "industry" instead of "label" and "value"
this.state = {
interested_industries: [{id:"ANY", industry:"ANY"}]
}
And in Select component:-
<Select
name="interested_industries"
options={industries}
value={interested_industries}
getOptionLabel={ x => x.id}
getOptionValue={ x => x.industry}
onChange={this.handleSelect}
isMulti
/>
defaultValue accepts an object or array of objects.
here an object can be like this :
defaultValue = {{ value: 0, label: "John" }}
This is also one way:
defaultValue = { array1[0] }
If you want array of objects for multiple options (isMulti) you can do this:
defaultValue = { array1.map(ele => ele) }
Where array1 is an array of objects.
array1 = [
{ label: "John", value: 0 },
{ label: "Indiana", value: 1 },
{ label: "Stark", value: 2 },
];
This solution worked for me. I hope this helps you too.
You can set defaultValue without index
<Select
defaultValue={existingItems}
onChange={(option) => onChangeSelect(option)}
closeMenuOnSelect={false}
components={animatedComponents}
isMulti={true}
options={options}
/>
But for this to work you need await loading items from defaultValue if you loading from server
For Example my full code
{!kindsByRestaraunt.loading ? (
<Select
defaultValue={existingItems}
onChange={(option) => onChangeSelect(option)}
closeMenuOnSelect={false}
components={animatedComponents}
isMulti={true}
options={options}
/>
): ""}
According to React documentation, you can do this:
<select multiple={true} value={['B', 'C']}>
Where B, C are the default value you want to have selected.

How do you set <select> value/option in edit/new template - ExpressJS

I'm trying to use a partial to share a _form.html across an new.html and edit.html templates in ExpressJS. The problem is with the select tag.
How do you get a select HTML element to have the correct option selected in an edit form? If you use
<select value="#{blob.kind || ''}">
The select doesn't show the option whose value is equal to the blob.kind.
In order to specify a selected option, a selected attribute needs to be added to the option element: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select
Assuming the blob.kind property is a value string, you could write the Jade for your select and option elements as follows:
-
var options = [
{value: 'option1', text: 'Option 1'},
{value: 'option2', text: 'Option 2'},
{value: 'option3', text: 'Option 3'},
{value: 'option4', text: 'Option 4'}
];
select
each obj in options
if (blob.kind === obj.value)
option(value= obj.value, selected)= obj.text
else
option(value= obj.value)= obj.text
For future reference, Jade has been renamed to Pug.
I used to do this as follows:
select
each obj in options
option(value= obj.value, selected=blob.kind === obj.value ? true : false)=
obj.text
Sean's suggestion is excellent, but his syntax didn't quite work for me. Here's what I ended up with:
- const stateOptions = [{value:'AL', text:'Alabama'}, ...]
select#state(name='state' required)
each option in stateOptions
if (option.value === meeting.state)
option(value=(option.value) selected) #{option.text}
else
option(value=(option.value)) #{option.text}