FlutterFire update Array instead of replacing it - firebase

so the menus field stores maps inside of an array/List. But when i want to add a map to menus it replaces all the existing ones with the new one, instead of adding a new one, here my code:
Menu menuObj = Menu(
name: menuName, categories: [
Categories(
name: categoryName,
),
]);
FirebaseFirestore.instance.doc('menus/${FirebaseAuth.instance.currentUser!.uid}')
.set({
'menus': [
menuObj.toJson(),
]
}, SetOptions(merge: true));

I had to use this code instead:
FirebaseFirestore.instance
.doc('menus/${FirebaseAuth.instance.currentUser!.uid}')
.set({
'menus': FieldValue.arrayUnion([menuObj.toJson()])
}, SetOptions(merge: true));
Important part is this: FieldValue.arrayUnion([menuObj.toJson()]).

Related

How to get included model data count in prisma with where clause?

i need to get user details with post count(Number of posts for today).
const usersWithCount = await prisma.user.findMany({
select: {
_count: {
select: {
posts: {
where: {
createdAt: moment().format("YYYY-MM-DD"),
},
},
recipes: true,
},
},
},
})
You cannot filter in relations count, this is not currently supported by prisma.
Here is the Feature Request for adding filters in relations count.
In your use case you can get filtered relations as described below:
const usersWithCount = await prisma.user.findMany({
select: {
posts: {
where: {
createdAt: moment().format("YYYY-MM-DD"),
},
},
recipes: true
},
});
In the response of the above query you will get posts array with records satisfying your where condition, you can use the array's length as a count.

What is the way to update or insert a record on Firebase with Flutter?

I have a collection users like this:
[{
'uid' : '1',
'favourites' : [
{ // fav1 },
{ // fav2 },
{ // fav3 },
etc
]
},
{
'uid' : '2',
'favourites' : [
{ // fav1 },
{ // fav2 },
{ // fav3 },
etc
]
},
etc
]
In some situations I have to update the favourites collection with a new "fav" and I can do that in this way:
final doc = FirebaseFirestore.instance.collection('users').doc(userId);
doc.update({ 'favourites': FieldValue.arrayUnion([fav.toJson()]) });
however the item might be not there so I have to use doc.set to create a new item. As I am new with Firebase, what is a "best practice" for a problem like this (if the element is not there create it first, otherwise update it)?
You can specify a merge option to set, which does precisely what you want:
doc.set({ 'favourites': FieldValue.arrayUnion([fav.toJson()]) }, SetOptions(merge : true))
You can use a function that can check if there is a doc or not with that specific info. And you can create a if-else statement depends on if there is a doc named like that or not.
An example function for checking the doc:
Future<bool> checkIfDocExists(String stuffID) async {
try {
/// Check If Document Exists
// Get reference to Firestore collection
var collectionRef = FirebaseFirestore.instance
.collection('favorites');
var doc = await collectionRef.doc(userId).get();
return doc.exists;
} catch (e) {
throw e;
}
}

How to obtain a specific document from Firebase in Vue

How to obtain and display a single document from a list of documents from Firebase Firestore data?
I’m able to grab the collection of documents and display the information but I just want to grab one so I can display it elsewhere without duplicating multiple elements with data.
Firebase example:
DocID: title - “Pizza”
DocID: title - “Pancakes”
DocID: title - “Cereal”
Vue template example:
H1-tag {{display the title of Pizza here}} h1tag
Is there a way to do this without having multiple h1 elements with different titles?
DocID: title - “Pizza” DocID: title - “Pancakes” DocID: title - “Cereal”
One of the options:
Must be an array or convert to an array. And then receive data from it.
items: [
{
title: 'Pizza',
price: ''
},
{
title: 'Pancake',
price: ''
},
{
title: 'Cereal',
price: ''
}
]
<h1>{{items[0].title}}</h1>
vue3
setup () {
const items = ref([])
db.collection('products').onSnapshot((snapshotChange) => {
items.value = []
snapshotChange.forEach((doc) => {
items.value.push({
key: doc.id,
title: doc.data().title,
price: doc.data().price
})
})
})
return {
items
}
}

Docusign create envelope and apply template to newly added document Laravel 5.5

Below is how i am sending doc for sign i need to run AutoPlace on this attached doc but iam not able to make it work. This code is working but not placing autoplace that i had set in this template.
$client = new DocuSign\Rest\Client([
'username' => config("docusign.DOCUSIGN_USERNAME"),
'password' => config("docusign.DOCUSIGN_PASSWORD"),
'integrator_key' => config("docusign.DOCUSIGN_INTEGRATOR_KEY"),
]);
$templateRole = $client->templateRole([
'email' => <email>,
'name' => <name>,
'role_name' => 'Client',
]);
$envelopeDefinition = $client->envelopeDefinition([
'status' => 'sent',
'email_subject' => 'Signature Required On Your Order ',
'template_id' => '<docusign template id>',
'template_roles' => [
$templateRole,
],
]);
$doc = Storage::disk('local')->url('mypdf.pdf');
$envelopeOptions = $client->envelopes->createEnvelopeOptions([
'documents' => [
'documentBase64' => base64_encode($doc),
'name' => 'mypdf.pdf',
],
]);
$envelopeSummary = $client->envelopes->createEnvelope($envelopeDefinition, $envelopeOptions);
print_R($envelopeSummary);
die();
Can you please suggest me how can i add that code.. Thanks in advance.
You are using wrong code pattern. With your code you can either apply template or you can add document to the envelope but you will not be able to apply template to the document. To apply a template to the document, you need to use Composite Template. If you have anchor strings (autoplace) present in both the server template and the added document then with composite template you will replace the server template document with the added document. An example would be like below. Server Template - 1afc0348-e853-4a0c-92db-06101168eb4d has a document with the anchorstring (autoplace), and FileName - "Added Document Agreement" in the "document" node has new document on which autoplace anchor string needs to be applied from the server template. Below code will show how to achieve this using composite template.
{
"compositeTemplates": [
{
"document": {
"documentBase64": "<Base64>",
"documentId": "1",
"fileExtension": "pdf",
"name": "Added Document Agreement"
},
"inlineTemplates": [
{
"recipients": {
"signers": [
{
"email": "email#gmail.com",
"name": "John Doe",
"recipientId": "1",
"roleName": "InternalSigner",
"routingOrder": "1"
}
]
},
"sequence": "2"
}
],
"serverTemplates": [
{
"sequence": "1",
"templateId": "1afc0348-e853-4a0c-92db-06101168eb4d"
}
]
}
],
"status": "sent"
}

dgrid JsonRest store not working

I have the following:
require([
"dojo/dom",
"dojo/on",
"dojo/store/Observable",
"dojo/store/JsonRest",
"dojo/store/Memory",
"dgrid/OnDemandGrid"
], function (dom, on, Observable, JsonRest, Memory, OnDemandGrid) {
var store = new JsonRest({
target: 'client/list',
idProperty: 'id'
});
var grid = new OnDemandGrid({
columns: {
"id": "ID",
"number": "Name",
"description": "Description"
},
sort: "lastName",
store: store
}, "grid");
});
client/list is a rest url returning a json object {data:[...]}, but the content of the list never shows up :/
I think the problem is caused by the async data loading, because with a json hard coded object the content show up
EDIT :
I've succeeded in achieving this by using a dojo/request, but the JsonRest shouldn't normally act the same way ? Can someone point me to the right direction ?
require([
'dojo/dom',
'dojo/on',
'dojo/store/Memory',
'dojo/request',
'dgrid/OnDemandGrid'
], function (dom, on, Memory, request, OnDemandGrid) {
request('client/list', {
handleAs: 'json'
}).then(function (response) {
// Once the response is received, build an in-memory store with the data
var store = new Memory({ data: response });
// Create an instance of OnDemandGrid referencing the store
var grid = new OnDemandGrid({
store: store,
sort: 'id', // Initialize sort on id, ascending
columns: {
'id': 'ID',
'number': 'Name',
'description': 'Description'
}
}, 'grid');
console.log(store);
on(dom.byId('queryForm'), 'input', function (event) {
event.preventDefault();
grid.set('query', {
// Pass a RegExp to Memory's SimpleQueryEngine
// Note: this code does not go out of its way to escape
// characters that have special meaning in RegExps
description: new RegExp(this.elements.last.value, 'i')
});
});
on(dom.byId('queryForm'), 'reset', function () {
// Reset the query when the form is reset
grid.set('query', {});
});
});
});
Ok problem found :/
My "client/list" url was returning a json object like this:
{data: [{id:"1", label: "test"}, {id:"2", label: "test"}]}
Turns out that the JsonRest object is already encapsulating data in a data node, so by returning a json like this:
{[{id:"1", label: "test"}, {id:"2", label: "test"}]}
everything worked fine :)

Resources