How to print block_data based on block_type key value in dart - dart

I have a method where i iterate through list of objects. For each object i want to print the value of 'block_data' based on "block_type" in the order of above to below. Notice that sometimes the block_type title is above text and sometimes its below text in the list of objects.
Sometimes i have other block_types like graph-pie-chart and i have block_labels for the chart and the block_data for the chart is also in a list based on block_labels. And all the block_type in the List coul be something else and another order. But i still want it in the order of the List of objects i get like the example below. I wonder how i can achieve this with dart?
class Book {
getBookInfo() {
final List listOfItems = [
{"block_type": "title", "block_data": "Books"},
{"block_type": "text", "block_data": "This is the textblock of books"},
{"block_type": "text", "block_data": "This is the textblock of publishers"},
{"block_type": "title", "block_data": "Publishers"},
{"block_type": "graph-pie-chart", "block_labels": ["Total sold","Sold copies","Reviews"], "block_data": ["3000", "100", "10"]},
{"block_type": "button", "link": "<link to a bookshop>"},
];
List selectedItem = listOfItems;
selectedItem.forEach((index) {
}
;
});
}
}

While strictly speaking, you are not incorrect to call each element of the list an object, they are more precisely of type Map<String,String>
You can use .where() to filter out maps that do not have a key of block_type and value of the block type that you need, then do your .forEach() to print the value you want.
You also might consider defining a class type to use instead of a Map in your listOfItems

Related

Symfony form not working properly if a field is empty or not exists

To edit the entity training, I use the TrainingFormType like this:
public function editTraining(Training $training) {
$form = $this->createForm(TrainingFormType::class, $training);
$form->submit($request->request->all());
The form has a field title:
->add('title', TextType::class, [
'constraints' => [
new NotBlank(),
new Length(null, null, 50)
]])
If I pass in the request an empty value into the field title "title" : "", I get an error 500:
"Expected argument of type "string", "null" given at property path "title".". I expected here an error from the form, not the InvalidArgumentException
When using the same form for creating of a new training, everything works fine, a validation error is generated, as expected:
"title": {
"errors": [
"This value should not be blank."
]
},
It's how I use the form when creating a new training:
$training = new Training();
$form = $this->createForm(TrainingFormType::class, $training);
$form->submit($request->request->all());
How to solve this problem? I thought, I can resolve it using an so called IgnoreNonSubmittedFieldListener, but on this way it also doesn't work. I get the same error.
One possible solution is to set a sensible default in the Training entity for that field:
// in Training.php
// ORM mapping omitted:
private string _title = '';
Then when a new entity is created it will have that value.

How to find an object by a property from a List of List of objects in dart?

Hello I am new to dart and trying to find an item by property name in a list of list.
class Product{
String id;
String title;
Product(this.id,this.title);
}
void main(){
List<List<Product>> allProdcuts=[
//New Prodcuts
[
Product("1","Hammer"),
Product("3","Nails"),
Product("2","Screws"),
],
futureItems,
//Old Prodcuts
[
Product("4","Rock"),
Product("5","Paper"),
Product("6","Scissor"),
],
//Rare Items
[
Product("7","Plank"),
Product("8","Wires"),
Product("9","Box"),
],
];
print(allProdcuts.where((itemsList)=>itemsList.contains((product)=>product.title='Wires')));
//Returns ()
}
I have tried using for a single List:
List<Product> futureItems= [
Product("101","Galactic Hammer"),
Product("301","Galactic Nails"),
Product("201","Galactic Screws"),
];
print(newProduct.firstWhere((p)=>p.title=='Hammer'));
//Instance of 'Product'
Also tried this:
print(allProdcuts.map((itemList)=>itemList.firstWhere((p)=>p.title=='Nails')));
// Bad state: No elementError: Bad state: No element.
But there is an element with the title='Nails'.I don't understand what I am doing wrong.
You are calling itemList.firstWhere((p)=>p.title=='Nails') on each list, also the ones with no element with title "Nails". Since firstWhere throws if there is no matching value, it does that for two of your three lists. Also, in the example, itemsList.contains(...) does not take a callback, so you are just checking whether a function is in the list, which it isn't. You might want to use any for that, but it won't solve the problem here.
To do this efficiently, I'd probably create helper function:
Product findByTitle(List<List<Product>> allProducts, String title) {
for (var products in allProducts) {
for (var product in products) {
if (product.title == title) return product;
}
}
// Or return `null`.
throw ArgumentError.value(title, "title", "No element with that title");
}
The return in the middle allows you to skip out of the double iteration the moment you have a match, something which is harder to do with firstWhere/map/forEach etc.
One alternative solutions would be:
var product = allProducts.expand((l) => l.where((p) => p.title == title)).first;
which finds all the products with the given title and flattens them into a single iterable, then picks the first one (if there are any). Because iterables are lazy, it will actually stop at the first match.
There are many ways to solve this.
One example is to use the forEach() method:
allProdcuts.forEach(
(List<Product> l)=>l.forEach(
(Product p){
if (p.title=="Nails")
print(p.id);
}
)
);
The for each method receives a function and applies this function to every element on the list. If you have a lists of lists, you can do this twice to get a function applied to each element of the sub lists.
The above code prints 3, which is the desired result.
Another solution would be to flatten the list first, so you can have an easier search later.
print(allProdcuts.any((innerListOfProducts) =>
innerListOfProducts.any((product) => product.title == 'Wires')));
This code will return true if 'Wires' is in the inner list, and false otherwise.

Unable to set dynamic dropdown value in Zapier CLI trigger

I have my app in Zapier CLI. I have created a trigger to set dropdown values for a particular action step during zap creation.
The data comes like this :
{ "data": {
"account_status": {
"field_name": "account_status",
"field_label": "Status",
"field_type": "list",
"field_length": "50",
"field_items": "Active|Inactive|444|Closed",
"required": "0",
"related_module": "",
"related_field_name": "",
"join_table": "",
"join_lhs_field_name": "",
"join_rhs_field_name": "",
"related_data_field": ""
},
}
}
Here is my code:
Now I am trying to set the data for the dynamic dropdown using field_items value from the above result like this:
return responsePromise
.then(response => JSON.parse(response.content ) )
.then(data => {
const account_status_list = data.data.account_status.field_items;
const account_status_arr = account_status_list.split("|");
return account_status_arr.map(function(e){
e.id = e
return e
})
})
my input field for the dynamic dropdown trigger is:
{
key: 'account_status',
label:'Account Status',
required: false,
dynamic: 'account_status.account_dropdown.id'
}
On clicking the dropdown I get this error
Can anyone suggest where I am going wrong or what may I do to resolve this ?
David here, from the Zapier Platform team.
The issue is that Zapier expects an array of objects and you're returning an array of strings. It seems like you're trying to make an id field in your code snippet, but calling "Active".id = "Active" won't make an object.
Instead, you should change your map function to be something like the following:
return account_status_arr.map(function(e){
return {id: e}
})
The other thing you'll probably need to tweak is how your dynamic dropdown is set up. It's a period-separated string that follows the format trigger_key.id_key.label_key. The id and label can be the same key; it really depends on what data you need to send to the API (the label is just for show, the id is what's actually sent). In the dynamic field, you'll have a dyanmic property that'll be account_status.id.id.
There are docs here.

dymamic Schemas and nested Maps in Avro

I'm new to Avro, and am trying to write some code to serialize some nested objects.
The structure of the objects looks like this:
class Parcel {
String recipe;
Map<Integer, PluginDump> dumps;
}
class PluginDump {
byte[] state;
Map<String, Param> params;
}
class Param {
Type type; //can be e.g. StringType, BooleanType, etc
Object value;
}
So I can't use a static avro schema - each PluginDump will have a different schema depending on the types within it.
I have written some code which can generate a Schema based on an individual PluginDump.
So when serializing a Parcel, how do I 'put' each PluginDump entry?
Here is my code:
Schema parcelSchema = AvroHelper.getSchema(p);
GenericRecord parcelRecord = new GenericData.Record(parcelSchema);
parcelRecord.put("recipe", p.getRecipe().toJson());
for (Map.Entry<Integer, PluginDump> entry : p.getDumps().entrySet()) {
PluginDump dump = entry.getValue();
Integer uid = entry.getKey();
Schema dumpSchema = AvroHelper.getSchema(dump);//will be different for each PluginDump
parcelRecord.put(????
Any ideas?
I have a feeling my approach is wrong, but I can't find any examples in the documentation of dynamic schema generation or nested maps.
1 When you get GenericRecord parcelRecord = new GenericData.Record(parcelSchema); you have two fields in your record: recipe and dumps, so you can't iterate through the dumps, you must put prepared map with dumps in the second field of record, just like you did it for recipe: parcelRecord.put("dumps", dumps);. But in this case, you'll get ClassCastException, because PluginDump cannot be cast to org.apache.avro.generic.IndexedRecord, so you need to put in parcelRecord a Map of GenericRecords. Also you need this for Map<String, Param> params, cause Param cannot be cast to IndexedRecord too.
2 Then, I think that its better to use Lists instead of Maps, cause avro not very good enough to work with Maps with different types of keys and values.
3 About the Param class: if you will use auto-generated schema, Param class will be presented like this.
"type": "record",
"name": "Param",
"fields": [
{
"name": "type",
"type": {
"type": "record",
"name": "Type",
"namespace": "java.lang.reflect",
"fields": []
}
},
{
"name": "value",
"type": {
"type": "record",
"name": "Object",
"namespace": "java.lang",
"fields": []
}
}
]
As far as avro uses java.lang.reflect, you will lose type field after deserialization, avro will not know what type it was.
If you want to generate avro-schema manually for each Param, considering its type, you can do something like this (I used ClassUtils.getClass from apache commons-lang3, cause standart Class.forName method doesn't always work properly):
public Schema getParamSchema() throws ClassNotFoundException {
List<Schema.Field> fields = new ArrayList<>();
fields.add(new Schema.Field("key", Schema.create(Schema.Type.STRING), "Doc: key field", (Object) null));
Schema.Field f = new Schema.Field("type", ReflectData.get().getSchema(ClassUtils.getClass(((Class) this.type).getName())), "Doc: type field", (Object) null);
f.addProp("java-class", ((Class) this.type).getName());
fields.add(f);
fields.add(new Schema.Field("value", ReflectData.get().getSchema(value.getClass()), "Doc: value field", (Object) null));
return Schema.createRecord(((Class) this.type).getName() + "Param", "Doc: param record", this.getClass().getPackage().getName(), false, fields);
}
But in this case, avro will throw ClassCastException, because it can't cast Class to Boolean, Integer etc. I always had a lot of problems working with avro and java Types and Classes.
So the best advice i think will be to change you model (Parcel, PluginDump and Param i mean) to have less problems with avro. For example you can store type name like a string, and get a Type with reflection after deserializing.

SAPUI5 - complex model binding

I have this json model:
model/data.json
{
"orders" : [
{
"header" : { "id" : "00001", "description" : "This is the first order" },
"items" : [
{ "name" : "Red Book","id" : "XXYYZZ" },
{ "name" : "Yellow Book", "id" : "AACCXX" },
{ "name" : "Black Book", "id" : "UUEEAA" },
]
},
{
// another order with header + items
},
.....
]
}
and I'm assigning it onInit to the view, like this:
var model = new sap.ui.model.json.JSONModel("model/data.json");
sap.ui.getCore().setModel(reqModel);
I'm trying to display a list of orders in the first view (showing the id), like this:
var list = new sap.m.List({
id: "mainList",
items: []
});
var items = new sap.m.ActionListItem({
text : "{id}",
press : [ //click handler, onclick load the order details page ]
});
list.bindItems("/orders", items);
.... // add list to the page etc etc
What I cannot do, is connect each order to its header->id.. I tried
text: "/header/{id}"
text: "{/header/id}"
in the items declaration, and
list.bindItems("/orders/header", items)
in the list binding, but none of them works.. The id value is not displayed, even though a "blank" list item is shown..
Any idea? What am I doing wrong?
Thank you
The solution was one of those I tried (but I don't know why it didn't work at that time)
text: "{/header/id}"
The ListItem acts as a Template for a list/array of objects. That's why you bind it against an array structure in your data:
list.bindItems("/orders", itemTemplate)
That makes bindings of the ListItem relative to /orders and therefore your item should look like this without leading '/' (absolute paths would look like this /orders/0/header/id asf.):
var itemTemplate = new sap.m.ActionListItem({
text : "{header/id}",
press : [ //click handler, onclick load the order details page ]
});
Not quite sure how you made it work the way you have shown... May be it's not as picky as I thought.
Btw: For whatever reason the ResourceModel builds an exception of that syntax. You can always omit the leading '/' when dealing with ResourceModels (probably because they do not allow nested structures).
BR
Chris
Cannot add comments yet, therefore an answer to you solved Problem, that could answer the initial problem. (And inform People using that example in any way)
In the current code listing you use the variable "reqModel" to set the model, but the variable with the model in it is named "model" in the line before. Maybe that was the first reason why both of your examles would not work?
Perhaps this error was cleared on rewriting some passages while testing.
greetings! -nx

Resources