In KeystoneJS, how can I make all values initially selected in a Relationship field using many: true? - keystonejs

I am using KeystoneJS. I have a relationship field in my Post model that references another model called Device. I am using many: true to allow users to select multiple items from the Device model.
Is there a way to have them all initially selected when creating a Post?
Right now my relationship field looks like this:
availableDevices: {
type: Types.Relationship,
ref: 'Device',
many: true
}

In your model definition, you can add pre-processing steps to populate fields that you'd like to have a default value in the relationship. I haven't done this with a many relationship, but I have done it with a relationship like this:
Report.schema.pre('save', function (next) {
this.wasNew = this.isNew;
if (!this.employee) {
this.employee = this.createdBy;
}
if (!this.timeEnteredTheHomeStr) {
if(!this.timeEnteredTheHome) {
this.timeEnteredTheHome = Date.now
}
this.timeEnteredTheHomeStr = String(this.timeEnteredTheHome);
}
next();
});
When someone creates a new report object, the employee field is automatically set to the user object referenced in the createdBy field.

Related

Sequelize through association attributes in Pug

In a nutshell, I cannot access though association attributes in Pug, only id and created_at can be displayed.
I have Item and Order models, they have many to many relationship though OrderItem model which is hooked to order_items table which works correctly on an API. When orders are sent to Pug using res.render, the resulting object has items which have nested order_items as 'through attributes'. Declared 'through association' attributes in the controller are id, payment, quantity and created_at and they are all seen in the object sent to res.render.
The association is defined in the Order model as:
static associate(models) { Order.belongsToMany(models.Item, {
as:'items',
through: 'order_items',
foreignKey: 'order_id',
otherKey: 'item_id'
})
}
On the Item model, similar association is declared with a few changes. On the controller, this is how I call a specific order:
const foundOrder = await Order.findOne({
where: { id: req.params.id },
include: {
model: Item,
as: 'items',
through: { attributes: ['id', 'quantity', 'payment', 'created_at']}
}
})
In views/orders/details I wanted to view details of a specific order, in the rendered result I only got item.name, item.order_items.id and item.order_items.created_at but failed to get item.order_items.quantity or item.order_items.payment which should be on the same tree level as the id.
When I try to loop through the object and console.log(item.order_items) in the server console I see the entire nested object and indeed quantity and payment are there. They are in string format as I have been trying to see if them being INTEGER was the problem but that did not solve anything.
{
"id":"2ac16f14-75c8-4bb6-b693-f5dc825eb33e",
"quantity":"34",
"payment":"136000",
"created_at":"2022-09-22T10:30:10.000Z"
}{
"id":"b7f06b43-ac79-4fc6-8e46-01c6c5a8cfd2",
"quantity":"80",
"payment":"320000",
"created_at":"2022-09-22T10:30:10.000Z"
}
Likewise, when I put console.log(item.order_items.id) or created_at in the same style in the order page in Pug I get the values for the two items that are attached with that order.
"2ac16f14-75c8-4bb6-b693-f5dc825eb33e"
"b7f06b43-ac79-4fc6-8e46-01c6c5a8cfd2"
On the other hand, if I put in the same view/orders/details.pug the script console.log(item.order_items.quantity) instead of getting 34 and 80, I get:
unidentified
unidentified
What have I done wrong?
Is this a bug with Pug?

Is there a way to present One2Many Relation in correct way in realm?

I have a very simple schema structure in my mobile app:
export const DepositSchema = {
name: "Deposit",
properties: {
uuid: "string",
payments: "Payment[]",
},
primaryKey: "uuid",
};
export const PaymentSchema = {
name: Instance.Payment,
properties: {
payment_amount: "string",
payment_method: "string",
deposit: {
type: "linkingObjects",
objectType: "Deposit",
property: "payments",
},
},
primaryKey: "uuid",
};
So means that every deposit can have zero, one or few payments (it can be paid partially), but one payment should be assigned only to one deposit
I put Payment objects to Realm database as below:
database.manager.write(() => {
if (payment.deposit_uuid) {
deposit = database.manager.objectForPrimaryKey("Deposit", payment.deposit_uuid);
}
const createdDbPayment = database.manager.create(
Instance.Payment,
{
...payment,
status: STATUS_TO_IGNORE,
},
Realm.UpdateMode.Modified,
);
if (deposit && createdDbPayment && deposit.payments.filtered("uuid == $0", payment.uuid).length == 0) {
deposit.payments.push(createdDbPayment);
}
});
Meanwhile, when i try to log payment object gotten from Realm Database it looks that instead of one deposit assigned to this payment, I got array of deposits. (ofc with only one object but it's very annoying)
The question is: Is there a way to connect this schema to present One2Many (not many2many) relationship?
I would like to achieve:
payment.deposit.uuid instead of payment.deposit[0]?.uuidThanks for help
I would like to achieve: payment.deposit.uuid instead of
payment.deposit[0]?.uuid
Whenever LinkingObjects are used, they allow "automatic" navigation back to the parent object - however, they also create a many-many relationship by their nature.
That's why it's LinkingObjects (plural) not LinkingObject.
If there is only ever one to link back to, then your code will work with the index 0 being required to reference to the first element
payment.deposit[0]?.uuid
The benefit of LinkingObjects is the backlink is created for you (it's more of a calculated property than a managed property). On the other hand it's not exactly what you want.
So you'll need to create the backlink manually - and in some cases it makes more sense but you loose the 'automatic' relationship. Using pseudo-code
export const DepositSchema = {
name: "Deposit",
properties: {
payments: "Payment[]"
export const PaymentSchema = {
name: Payment,
properties: {
parent_deposit: "Deposit"
I would suggest adding a "addPayment" function to add a payment to the Deposit. When a payment is passed to the Deposit property, the parent Deposit will add its reference to the payment and then add it to the Payments List.
That will create a forward relationship from Deposits to multiple Payments and then a single backward relationship from Payment back to its parent Deposit.
Then the graph can be transversed in both directions.

Grouping WSAPI data store by Parent Name

I am creating a rallygrid component and would like to have the grid items grouped by their parent's Name attribute (bonus if I could also display the ID of the parent). I added the groupBy:'Parent' configuration to the storeConfig of the grid and was surprised that no results were returned. I also tried using groupBy:'Parent.Name' but still nothing.
I know this is possible with other fields such as Owner, but I'm at a loss as to why the Parent wouldn't be usable as well. Is this a bug, or am I setting the config up incorrectly?
Thanks
Change the storeConfig to keep the records from trying to update after being grouped:
storeConfig : {
remoteSort : false,
remoteGroup : false,
remoteFilter : false,
}
Add a listener to the load event which assigns a root level property to the record and groups by that record value. (For some reason store.group('Parent.Name'); doesn't work.)
load: function(store) {
store.each(function(record) {
record.set('ParentName', record.get('Parent') && record.get('Parent').Name || '-- Unparented --');
});
store.group('ParentName');
}
I thought it was a bug with the SDK too, but per WS API documentation, Parent, unlike Owner, or Feature is not sortable.
So when I use groupField: 'Parent' the grid is empty, and response showed error:
Ext.data.JsonP.callback6({"QueryResult": {..., "Errors": ["Cannot sort using attribute Parent"]
It is trying to sort by Parent, but Parent attribute is not sortable. So the SDK ran into a WS API limitation.
On a side note, I did not use groupBy, instead I used groupField on the store (in this example I grouped by Kanban field) :
var myStore = Ext.create('Rally.data.WsapiDataStore',{
model: 'UserStory',
groupField: 'c_MyKB',
//...
});
And then used features: [{ftype:'grouping'}] in the grid.
this._myGrid = Ext.create('Ext.grid.Panel', {
store: myStore,
features: [{ftype:'grouping'}],
//...

How can I create a new model that is an extention of an existing model with an additional field

Currently the additional field is calculted in the grid columnCfgs using an xtype of templatecolumn. I need to add this field to the grid data store so that it can be used to filter the grid data.
Model classes fields property is processed in a special fashion. Instead of replacing the parent class' ones as a normal property would, child fields are appended to them.
See this example:
Ext.define('Base', {
extend: 'Ext.data.Model'
,fields: ['foo','bar']
});
Ext.define('Extended', {
extend: 'Base'
,fields: ['baz']
});
var record = Ext.create('Extended');
record.fields.each(function(field) {
console.log(field.name);
});
That gives the following output:
foo
bar
id
baz

insert in sencha touch data store

Could someone please explain how the insert works to add a record in a datastore
with tha fields: "title", "info" and "price"?
because i tried some things and none of them work. and the sencha website doesnt make it very clear.
Adding a new item to an existing Store isn't that hard actually.
First of you will need to configure your model and store. In your question you name the fields 'title, 'info' and 'price'.
Model:
Ext.regModel('myModel', {
fields: [
{name: 'id', type: 'int' },
{name: 'title', type: 'string' },
{name: 'info', type: 'string' },
{name: 'price', type: 'int' }
]
});
Next you configure the store that will hold the data, based on the above model. I think that, in your case, it should be a model without any data preloaded via, for example, JSON?
So lets make a localstorage (empty store). The Store consists of the model (myModel), you give it a storeID (so that you can later on reference the store by this ID). The proxy is localstorage and the unique ID of the Store will be the ID field of the Model.
Store:
var myStore = new Ext.data.Store({
model: "myModel",
storeId: "myStoreID",
proxy: {
type: "localstorage",
id: "id"
}
});
Now, suppose you have some kind of Form (in which the user can add input a title, info and price, and you want to add these items to the existing store on submittal.
Within the handler of the submittal button you now have to 'call' the store, and perform the add function on it. Within this add function you will have to define the params (the model params) and the data to insert.
Below I have used a mixture of fixed data and a variable to insert.
myStoreID.add({ title: "Mijn Titel", info: "Informatie, price: prijsvar });
The store will now be filled will now be filled with an extra data-record which you can use. Lets say for example that the store is attached to a dataview, then you can perform:
dataView.update();
The above isn't a full tutorial, but I think this will help you along?
Just an update of the YDL answer.
As per the dataView should be related to the updated store, the last sentence dataView.update() should not be needed, due to the automatic update of the views related to a store when it change.
new Ext.DataView({
store: MyStore,
itemSelector: 'div.thumb',
tpl: thumbTpl
});
later, if I do the following, the new item should be displayed in views (List, DataView, etc.) that have MyStore as store.
MyStore.add(newItem);
HTH.
Milton Rodríguez.
If you are trying to pass in an object that was returned from a getValue() on your form, make sure that you run a
myStore.sync();
after you have called the add() method, or you wont see it in your browsers local store.
It is Very easy try these
// first get those values and store in locally
var A_select1=Ext.getCmp('select1').getValue(); // get value
localStorage.setItem("Adult1_select1",A_select1); // set localStore
var AdultSalutation={
'Adult1_select1':A_select1, // assign the value
};
var AdultSalutationstore = Ext.getStore('Adult_AdultSalutationstore'); // get store
AdultSalutationstore.add(AdultSalutation); // add object
AdultSalutationstore.sync(); // sync
AdultSalutationstore.load(); // load