I am looking for a way to increment a field in firestore like in this documentation.
shard_ref.update("count", firebase.firestore.FieldValue.increment(1));
The only caveat is that I am trying to use firestore Client Sdk or the Admin Sdk for php.
What is a clean solution for incrementing a field in php. Does it require both read and write operations or is it possible with only write operation?
Firestore Client Sdk has the ability to increment a field. (use negative values to decrement).
You can use it in the following way to update the field with $field_name:
$data = [
[
'path' => $field_name,
'value' => \Google\Cloud\Firestore\FieldValue::increment($increment_value);
]
];
$doc_ref->update($data);
If you are using a batching you call it as follows
$data[$field_name] = \Google\Cloud\Firestore\FieldValue::increment($increment_value);
$batch->add_to_batch('update', $doc_ref, $data);
Here is additional reference
if you have more data you can do
$data = [
'name' => $name,
'email' => $email,
'likes'=> \Google\Cloud\Firestore\FieldValue::increment(1) // Add + 1
] ;
Related
UPDATE:
As it turns out, I need to enable this setting for data to show up, and using tabs is the correct thing to do.
When an envelope is sent, write the initial value of the field for all recipients
=================================================================
Not sure why this one is not mentioned in API properly ... but how does one go about filling template's custom data label with template?
So, I create a template like this:
$envelope_definition = new EnvelopeDefinition([
'status' => 'sent',
'template_id' => $args['template_id'],
]);
then I create a signer:
$signer = new TemplateRole([
'email' => $args['signer_email'],
'name' => $args['signer_name'],
'role_name' => 'signer',
]);
Here is where the disconnect happened, where do I add a pre-defined template value? I tried two things so far:
1. Add tabs to $signer like so, but by doing so, it ereases all field value in the final document,
new Tabs([
"text_tabs" => [
new Text([
"tab_label" => "price",
"value" => "123456789",
]),
],
]),
Call $envelope_definition->setCustomFields() , like this :
$envelope_definition->setCustomFields(new CustomFields([
'text_custom_fields' => [
'price' => new Text([
'tab_label' => 'price',
'custom_tab_id' => 'price',
'value' => '123456789',
]),
],
]));
It will throw me a C# error, which I don't understand at all:
Error while requesting server, received a non successful HTTP code [400] with response Body: O:8:\"stdClass\":2:{s:9:\"errorCode\";s:20:\"INVALID_REQUEST_BODY\";s:7:\"message\";s:718:\"The request body is missing or improperly formatted. Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[API_REST.Models.v2_1.textCustomField]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'customFields.textCustomFields.price', line 1, position 45.\";}"
API docs seems to be focusing on creating template and values adhoc ... anyone have something that works? Thanks a lot!
You can find valid PHP example here which shows how to prepopulate template tab values while creating an envelope.
You didn't follow the example correctly.
You didn't create a \DocuSign\eSign\Model\TextCustomField object.
Here it is from Amit's link:
# Create an envelope custom field to save the our application's
# data about the envelope
$custom_field = new \DocuSign\eSign\Model\TextCustomField([
'name' => 'app metadata item',
'required' => 'false',
'show' => 'true', # Yes, include in the CoC
'value' => '1234567']);
$custom_fields = new \DocuSign\eSign\Model\CustomFields([
'text_custom_fields' => [$custom_field]]);
$envelope_definition->setCustomFields($custom_fields);
At the moment I am adding a task to Cerb using the API (Docs: https://cerb.ai/docs/api/). I can add and edit comments on the task.
An extension is to add file uploads. The API documentation seems to be extremely limited in terms of file uploads and isn't helping much. I have based my current code on https://cerb.ai/docs/api/endpoints/records/#update, using a custom field linked to the task and posting directly to the API.
The process is as follows:
1 - User inserts information on a Laravel form
2 - Form is submitted, task is created
3 - If the user entered a comment or description, the controller then uses the ID from the newly created task toa dd the comment
4 - If the user adds a file, the controller should then use the same ID from the task to attach the file
Task and comment adding has been done through models, which were previously done directly through the API and reformatted once they worked.
Add Task:
$params = [
'title' => $request->input('title'),
'links' => ['project:'.$request->input('project')],
'priority' => $request->input('priority'),
'status_id' => 2
];
$due_date = $request->input('due');
if(!empty($due_date)){
$params['due'] = strtotime($due_date);
}
$success_task = $task->addUpdateRecord('tasks.add', $params);
Add Comment:
$params = [
'author__context' => 'bot',
'author_id' => 3,
'comment' => empty($comment_input) ? request()->comment : $comment_input,
'target__context' => 'task',
'target_id' => $task_id,
'author' => Auth::user()->name // custom field
];
$success = $comment->addUpdateRecord('comments.add', $params);
The addUpdateRecord() essentially does the same thing as the file upload as below:
$cerb = new CerbApi();
$out = $cerb->put($root.'records/file_bundle/1054.json?expand=custom_', $putfields);
$putfields contains a normal file upload object.
I'm getting the following error on request:
array:2 [▼
"__status" => "error"
"message" => "Unknown command (root/records/task/1054.json)"
]
(root removed for confidentiality)
Has anyone worked with this? Anyone able to assist?
Ended up getting it right by using the attachments record type https://cerb.ai/docs/records/types/attachment/ and creating a model for it with its own addUpdateRecord() method.
I then used the records API to do the post for the file as the first step instead of the last one:
$file_upload = new File;
// Get file contents
$data = file_get_contents($file);
// Base64 encode contents
$data = base64_encode($data);
$file_params = [
'name' => $file->getClientOriginalName(),
'content' => $data
];
// Do upload
$file_success = $file_upload->addUpdateRecord('files.add', $file_params);
// Only need to return the file ID to link it to the task
return $file_success["data"]["id"];
And then using the ID that was being returned to link it to the task:
$task = new Task();
$params = [
'title' => $request->input('title'),
'links' => [
'project:'.$request->input('project'),
'file:'.$file_id
],
'priority' => $request->input('priority'),
'status_id' => 2
];
I hope this helps someone in the future.
Note: Cerb API Version 9.2.0
This function is not in the Laravel documentation, I have found it in the source code however I am not completely sure how it should be used. For example, if I am working with products, I want to either insert or update a product in the database based on its UPC. If a product with the same UPC exists, update it with the new values. If not, insert the new values as a new product. How should this be done using this function?
Thank you!
Insert or update a record matching the attributes, and fill it with values.
updateOrInsert(array $attributes, array $values = [])
https://laravel.com/api/master/Illuminate/Database/Query/Builder.html#method_updateOrInsert
DB::table('products')->updateOrInsert(
[
'upc' => $request->get('upc'),
],
[
'upc' => $request->get('upc'),
'name' => $request->get('name'),
'vendor' => $request->get('vendor'),
'description' => $request->get('description')
]
);
I have a little REST API in my project. And ofcourse i use json as my return data to work with.
I am using symfony in the backend and angularJs in the frontend. At the moment i convert my entity to json by looping true my result and filling an data array to return as json.
EXAMPLE:
public function getAction($id)
{
$em = $this->getDoctrine()->getManager();
$warehouseId = $this->get('session')->get('warehouse');
$warehouse = $em->getRepository('BubbleMainBundle:Warehouse')->find($warehouseId);
$trip = $em->getRepository('BubbleMainBundle:Trip')->find($id);
$data = array(
'id' => $trip->getId(),
'driver' => $trip->getDriver(),
'status' => $trip->getStatus(),
'date' => $trip->getPlanningDate()->format('Y-m-d')
);
if ( count($trip->getStops()) > 0 ) {
foreach($trip->getStops() as $stop)
{
$data['assignedStops'][] = array(
'id' => $stop->getId(),
'status' => $stop->getStatus(),
'date' => $stop->getDeliveryDate()->format('Y-m-d'),
'sort' => $stop->getSort(),
'company' => array(
'name' => $stop->getToCompany()->getName(),
'lat' => $stop->getToCompany()->getLat(),
'lng' => $stop->getToCompany()->getLng(),
'address' => $stop->getToCompany()->getAddress(),
'zip' => $stop->getToCompany()->getZip()
),
);
}
} else {
$data['assignedStops'][] = '';
}
$response = new jsonResponse();
$response->setData($data);
return $response;
}
This works. But sometimes i have have (google chrome timeline) waiting responses of 6 seconds for just a simple query and json response.
Is looping true the entity to much? Or do i need another approach for converting my entities to json format?
thx anthony,
If you are using PHP 5.4 or above then considering using the JsonSerializable interface with your entities:
http://www.php.net/manual/en/class.jsonserializable.php
This will allow you to control how your entities are converted to JSON which will allow you to call json_encode directly on your entities without having to loop through and convert them to arrays.
As for the performance issue you'd need to profile your script to find out where the performance bottleneck is. From looking at your code one potential issue that you might want to look into is to make sure you are fetching all the data in your original query (i.e stops and companies) and you are not executing additional queries in the foreach loop to fetch the missing stop and company data.
I recommend you (since you are using Symfony2 as a backend and you need an API) to definitely try out this bundle... It's easy to use and to setup and as an extra you can also generate a nice documentation for it.
It will speed up your development and code.
I have been able to retrieve a full list of tags from all my EC2 instances using the PHP SDK but I'm struggling to filter the results down to a particular instance...
// Collect instance information
$sInstanceId = file_get_contents('http://169.254.169.254/latest/meta-data/instance-id'); // 'i-52da5b1f'
$sAvailabilityZone = file_get_contents('http://169.254.169.254/latest/meta-data/placement/availability-zone'); // 'eu-west-1b'
$sRegion = preg_replace('/^(.*)([0-9]{1})([a-zA-Z]{1})/', '$1$2', $sAvailabilityZone);
use Aws\Common\Aws;
use Aws\Ec2\Command\DescribeTags;
use Aws\Common\Enum\Region;
// Set up the global AWS factory
$oAWS = Aws::factory(array(
'key' => CONST_AWS_ACCESS_KEY,
'secret' => CONST_AWS_SECRET_KEY,
'region' => $sRegion
));
// Query EC2 for tags
$oEC2Client = $oAWS->get('ec2');
$oModel = $oEC2Client->describeTags()->toArray();
I've tried changing the call to describeTags to...
$oModel = $oEC2Client->describeTags(array(
"Filters" => array(
array("Name" => "resource-id", "Value" => $sInstanceId)
)
))->toArray();
But that seems to make no difference.
Could someone shed some light on this for me please?
The API docs for Ec2Client.describeTags show that Value should actually be Values and should be an array. Try the following:
$oModel = $oEC2Client->describeTags(array(
"Filters" => array(
array("Name" => "resource-id", "Values" => array($sInstanceId))
)
))->toArray();