How to break line in vue-multiselect on options - vue.js

Actually my main problem is about putting breakline inside options in javascript. I've problem with to break line on options when using multiselect with Vue.js.
Multiselect looks like this:
<multiselect v-model="form4.user_id"
:options="users"
:searchable="true"
:preselect-first="true"
:loading="is_loading_customers"
:internal-search="false"
:custom-label="with_customer_custom_label"
#search-change="get_customers_data"
track-by="id"
selected-label=""
select-label=""
deselect-label=""
placeholder="Ad, soyad, TC veya telefon numarası ile aratın..."
id="folder-status-select">
</multiselect>
My with_customer_custom_label function:
const with_customer_custom_label = ({ customer_detail }) => {
return `
TC: ${customer_detail.tc_identity_number} |
Ad Soyad: ${customer_detail.fullname} |
Telefon: ${customer_detail.phone}
`;
};
Options (users):
const users = ref([]);
// and then...
const get_customers_data = (query) => {
if (query.length > 2) {
is_loading_customers.value = true;
var axios_params = new URLSearchParams();
axios_params.append('query', query);
store.state.ax_req_auth.get('/search-customers', {
params: axios_params,
}).then(response => {
users.value = response.data;
is_loading_customers.value = false;
}).catch(error => {
console.log(error);
is_loading_customers.value = false;
});
}
};
response.data return example:
{
"id": "9832a4c7-38cb-4422-a8f3-18f024f31653",
"username": "customer",
"email": "customer#ferisoft.com",
"user_type": "4",
"status": "1",
"email_verified": "1",
"email_verified_at": "2023-01-11T10:26:43.000000Z",
"created_at": "2023-01-11T10:26:43.000000Z",
"updated_at": "2023-01-11T10:26:43.000000Z",
"customer_detail": {
"id": "9832a4c7-c4fe-4f4c-98b9-ab55c9e40265",
"user_id": "9832a4c7-38cb-4422-a8f3-18f024f31653",
"name": "Semih",
"surname": "ŞAHİN",
"tc_identity_number": "99999999990",
"phone": "05555555555",
"date_of_birth": "2023-01-11 10:26:43",
"profession": "0",
"salary": 22500,
"premium": 4000,
"start_date_of_work": "2023-01-11 10:26:43",
"close_to_customer_name": "Ferkan",
"close_to_customer_surname": "AKYAZICI",
"close_to_customer_tc_identity_number": "98989999992",
"close_to_customer_phone": "05527516134",
"email_address": "semih#ferisoft.com",
"profile_picture": null,
"notes": "Krediye şu şu şu sebeplerden dolayı ihtiyacım var, şu şu şu banka geçmişim var.",
"created_at": "2023-01-11T10:26:43.000000Z",
"updated_at": "2023-01-11T10:26:43.000000Z",
"fullname": "Semih ŞAHİN"
}
}
I want to embed with break line the option element to multiselect in the with_customer_custom_label function.
I already tried these:
return `
TC: ${customer_detail.tc_identity_number}\n
Ad Soyad: ${customer_detail.fullname}\n
Telefon: ${customer_detail.phone}
`;
or
return `
TC: ${customer_detail.tc_identity_number}` + "\n" + `
Ad Soyad: ${customer_detail.fullname}` + "\n" + `
Telefon: ${customer_detail.phone}
`;
But they always appear side by side. How can I show one under the other or with break line?

Related

Filter the JSON object where value is not empty or not null on created function on vue.js 3

I want to get the response.data (JSON Object) with value only in the new object on update form i.e. I want to filter it on computed/created on vue 3 - the json object received from API. My backend is Laravel 8 resource API.
On EditPatient.vue - The vue js is
export default {
data() {
return {
patient: {},
}
},
created() {
this.$axios.get('/sanctum/csrf-cookie').then(response => {
this.$axios.get(`/api/patients/${this.$route.params.id}`)
.then(response => {
this.patient = response.data // JSON object
/* .filter(function(item) {
item !== null || item !=='';
}) */ // this didn't work.
//I want to response.data and apply to this.patient object.
})
.catch(function (error) {
console.error(error);
});
})
},
}
response.data is
{ "created_by": 1, "firstname": "Kamal", "lastname": "", "sex": "M", "address": "Kathmandu, Bagmati, Nepal", "education": "Yes", "grade": "MSc", "alcohol": null, "alcohol_type": null, "weight": "", "kidney_disease": null, "high_bp": "No", "diabetes": null, "heart_attack_stroke": "No", "present_diabetes": "No", "systolic": "", "pulse_rate": "" }
On laravel api, I got a patient row as follow:
public function show($id)
{
$patient = Patient::find($id);
return response()->json($patient); // send data in json ojbect for frontend
}
It is better, If I can apply on backend too. Get the columns of single row which has value only.
To get only the object properties that are not empty/null:
Use Object.entries() on the response.data object to get an array of key/value pairs.
Use Array.prototype.filter() on the result, filtering out empty string and null.
Use Object.fromEntries() on the filtered result to create an object.
const input = { "created_by": 1, "firstname": "Kamal", "lastname": "", "sex": "M", "address": "Kathmandu, Bagmati, Nepal", "education": "Yes", "grade": "MSc", "alcohol": null, "alcohol_type": null, "weight": "", "kidney_disease": null, "high_bp": "No", "diabetes": null, "heart_attack_stroke": "No", "present_diabetes": "No", "systolic": "", "pulse_rate": "" }
const entries = Object.entries(input) // 1️⃣
const nonEmptyOrNull = entries.filter(([key,val]) => val !== '' && val !== null) // 2️⃣
const output = Object.fromEntries(nonEmptyOrNull) // 3️⃣
console.log(output)

How to convert from blob URL to binary?

I'm using ImageInput component inside an iterator to upload images in my create form and it generates a structure like this:
"data": {
"items": [
{
"id": 1,
"title": "test",
"subTitle": "test",
"additionalAttributes": {
"price": "3452345"
},
"images": [
{
"src": {
"rawFile": {
"path": "test.jpg"
},
"src": "blob:https://localhost:44323/82c04494-244a-49eb-9d0e-6bca5a3469f7",
"title": "test.jpg"
},
"title": "d"
}
]
}
],
"contact": {
"firstName": "test",
"lastName": "test",
"jobTitle": "test",
"emailAddress": "test#test.com",
"phoneNumber": "23234"
},
"theme_id": 1,
"endDate": "2020-06-19T22:27:00.000Z",
"status": "2"
}
}
What I'm trying to do is sending the image to an API for saving in a folder. Blob URL is an internal object in the browser son it can't be used in the API, so I tried to convert the Blob URL into a binary and send to API.
Following the tutorial I can not get the expected result. Here is my code:
I created a new dataProvider like this:
export const PrivateEventProvider = {
create: (resource: string, params: any) => {
convertFileToBase64(params.data.items[0].images[0].src.src).then(
transformedPicture => {
console.log(`transformedPicture: ${transformedPicture}`);
}
);
const convertFileToBase64 = (file: { rawFile: Blob }) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file.rawFile);
});
And I have this error
Unhandled Rejection (TypeError): Failed to execute 'readAsDataURL' on
'FileReader': parameter 1 is not of type 'Blob'.
enter image description here
So my question is, which is the correct way of uploading images to a folder using react-admin?

How could I render a ExtWebComponent Area Chart using Alpha Vantage stock data?

I would like to use Alpha Vanatage stock data in my ExtWebComponent chart. How could I fetch the data and render it in a Cartesian Area chart?
If you've generated an ExtWebComponents project, you could add these 2 files and declare the web component html element tag.
Usage
In the html file like index.html declare my-chart-area which is defined in the web component below.
AreaChartComponent.html - HTML Template
<ext-cartesian
width="1000px"
height="600px"
downloadServerUrl="http://svg.sencha.io"
shadow="true"
insetPadding="25 35 0 10"
axes='[{
"type": "numeric" ,
"position": "left" ,
"fields": [ "1. open" ],
"label": { "rotate": { "degrees": "-30" } },
"grid": { "odd": { "fill": "#e8e8e8" } },
"title": { "text": "Alphabet Inc Stock Data" , "fontSize": "20" }
},
{
"type": "category",
"position": "bottom",
"fields": "time",
"grid": "true",
"title": { "text": "Monthly", "fontSize": "20" }
}]'
legend='{
"type": "sprite",
"position": "bottom"
}'
series='[{
"type": "area" ,
"xField": "time",
"yField": [ "1. open", "2. high", "3. low", "4. close" ],
"title": [ "open", "high", "low", "close" ],
"style": { "stroke": "black" , "lineWidth": "2", "fillOpacity": "0.8" },
"colors": ["#003f5c", "#58508d", "#bc5090", "#ff6361", "#ffa600"]
}]'
platformConfig='{
"phone": { "insetPadding": "15 5 0 0" }
}'>
</ext-cartesian>
AreaChartComponent.js - Web Component
import template from './AreaChartComponent.html'
Ext.require([
'Ext.chart.theme.Midnight',
'Ext.chart.theme.Green',
'Ext.chart.theme.Muted',
'Ext.chart.theme.Purple',
'Ext.chart.theme.Sky',
'Ext.chart.series.Area',
'Ext.chart.axis.Numeric',
'Ext.chart.axis.Category'
]);
class AreaChartComponent extends HTMLElement {
constructor() {
super()
}
connectedCallback() {
this.innerHTML = template;
this._fetchChartData();
}
disconnectedCallback() {
}
attributeChangedCallback(attrName, oldVal, newVal) {
}
/**
* Fetch the chart data from https://www.alphavantage.co/ using an API Key.
*
* TODO Fetch your api key here: https://www.alphavantage.co/support/#api-key
*/
_fetchChartData() {
let me = this;
let apiKey = 'demo';
let stockSymbol = 'GOOGL';
let url = `https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=${stockSymbol}&apikey=${apiKey}`;
fetch(url)
.then(response => {
return response.json();
})
.then(json => {
return me._flattenData(json);
})
.then(jsonflatRows => {
me._renderChart(jsonflatRows);
})
.catch(err => {
console.log("error", err);
})
}
/**
* The goal is to flatten the nested json data, so it's easy to consume in the charts.
* #param json data
* #returns {*[]} array of json data
* #private
*/
_flattenData(json) {
console.log("json=", json);
let jsonTimes = json['Monthly Time Series']
let flatRows = [];
for (let jsonTime in jsonTimes) {
let row = {
"time": jsonTime
};
let jsonNestedTime = jsonTimes[jsonTime];
for (let nestedKey in jsonNestedTime) {
row[nestedKey] = jsonNestedTime[nestedKey];
}
flatRows.push(row);
}
return flatRows.reverse();
}
_renderChart(jsonflatRows) {
console.log('_renderChart jsonflatRows=', jsonflatRows);
let store = Ext.create('Ext.data.Store', {
fields: ["time", "1. open", "2. high", "3. low", "4. close", "5. volume"]
});
store.loadData(jsonflatRows);
let areaChartEl = this.querySelector('ext-cartesian');
areaChartEl.ext.bindStore(store);
}
}
window.customElements.define('my-chart-area', AreaChartComponent);
Source
https://gist.github.com/branflake2267/4652a5d7188dfe0b33d3d02a808d8d74

Unable to loop through data from SQLite call in React Native, Expo

I'm currently making a call to an SQLite local database in my react native
Expo app like so:
db.transaction(tx => {
tx.executeSql('select * from dr_report_templates', [], (_, { rows }) => {
const templateData = JSON.stringify(rows);
this.setState({ options: templateData, isLoading: false }, () => console.log(this.state))
});
},
error => {
alert(error);
},
() => console.log('Loaded template settings')
);
I'm returning the data and making it a JSON string with: JSON.stringify
Data appears like so:
Object {
"isLoading": false,
"options": "{\"_array\":[{\"id\":30,\"name\":\"SFR General\",\"description\":\"SFR1\"},{\"id\":31,\"name\":\"SFR Extended\",\"description\":\"SFR2\"},{\"id\":7790,\"name\":\"test_new_template\",\"description\":\"test_new_template\"},{\"id\":7792,\"name\":\"apart_1\",\"description\":\"apart_1\"},{\"id\":7793,\"name\":\"SFR\",\"description\":\"Single Family\"},{\"id\":7798,\"name\":\"Condo\",\"description\":\"Condo \"},{\"id\":7799,\"name\":\"Duplex\",\"description\":\"Duplex\"},{\"id\":7800,\"name\":\"Triplex \",\"description\":\"3\"},{\"id\":7801,\"name\":\"Apartments\",\"description\":\"Apartment complex\"},{\"id\":7802,\"name\":\"Commercial retail store \",\"description\":\"Storefront \"},{\"id\":7803,\"name\":\"5-10 unit\",\"description\":\"5\"},{\"id\":7804,\"name\":\"Commercial Industrial \",\"description\":\"Industrial \"},{\"id\":7805,\"name\":\"Industrial Property\",\"description\":\"RE\"}],\"length\":13}",
"selected": "",
}
Attempting to get values for just the first array element like so:
this.state.options[0]
does not work. I'm obviously doing something wrong in the way that I'm doing this but can't figure out what. Any ideas?
EDIT: I had also ran the query with out JSON.Stringify. The data returned like so with this "t" in front of it. I've never hard this before and I couldn't loop through it so that's why I did a JSON.stringify.
t {
"_array": Array [
Object {
"description": "SFR1",
"id": 30,
"name": "SFR General",
},
Object {
"description": "SFR2",
"id": 31,
"name": "SFR Extended",
},
Object {
"description": "test_new_template",
"id": 7790,
"name": "test_new_template",
},
Object {
"description": "apart_1",
"id": 7792,
"name": "apart_1",
},
Object {
"description": "Single Family",
"id": 7793,
"name": "SFR",
},
Object {
"description": "Condo ",
"id": 7798,
"name": "Condo",
},
Object {
"description": "Duplex",
"id": 7799,
"name": "Duplex",
},
Object {
"description": "3",
"id": 7800,
"name": "Triplex ",
},
Object {
"description": "Apartment complex",
"id": 7801,
"name": "Apartments",
},
Object {
"description": "Storefront ",
"id": 7802,
"name": "Commercial retail store ",
},
Object {
"description": "5",
"id": 7803,
"name": "5-10 unit",
},
Object {
"description": "Industrial ",
"id": 7804,
"name": "Commercial Industrial ",
},
Object {
"description": "RE",
"id": 7805,
"name": "Industrial Property",
},
],
"length": 13,
}
this.setState({ options: templateData._array, isLoading: false });
or change how you destructure in 3rd parameter of executeSql to:
(_, { rows: { _array } }) => {
const templateData = JSON.stringify(_array);
}
Why you're conveting it with JSON.stringify()? You can iterate over array or access it with array's key name.
NOTE: JSON.stringify() does not convert it to JSON. It converts to JSON string
The JSON.stringify() method converts a JavaScript object or value to a
JSON string, optionally replacing values if a replacer function is
specified or optionally including only the specified properties if a
replacer array is specified.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
You're actually converting your database response to string.
So Change
const templateData = JSON.stringify(rows);
to
const templateData = rows;
and use this array where you want.

React Native -- Loop through array of objects to return value

Data:
{
"contextTag": {
"value": "Bittersweet",
"valueLabel": "Bittersweet"
},
"tags": [
{
"name": "tag",
"value": "Creamy"
},
{
"name": "tag",
"value": "Colorful"
},
{
"name": "tag",
"value": "Bright"
}
],
"rating": 5,
"userNickName": "HelloGames",
"userLocation": "UK",
"title": "Great!",
"reviewText": "Yada yada yada yada",
"submissionTime": "30 Nov 16"
},
I currently have this working for getting contextTag valueLabels:
this.props.reviewData.reviews.map(
(o) => {
return o.contextTag && o.contextTag.valueLabel ? o.contextTag.valueLabel.trim() : '';
}
)
And this for tags:
this.props.reviewData.reviews.map(
(o) => {
return o.tags && o.tags.value ? o.tags.value.trim() : '';
}
)
But it's coming back empty. How do I loop through tags to grab each of the values?
You can cache the tags, then map over it to get the values. Like below:
const tags = this.props.reviewData.reviews.tags;
const tags_values = ( tags ? tags.map((tag) => (tag.value ? tag.value : '' ) : []); // this an array of the tags values.
Your code does not return what you want because the tags attributes is an array of objects, so to get the tag values you have to map over it as I did above.
Hope this helped.