I want to use database transaction but use the created id within the transaction.
DB::transaction(function () {
$user = User::insert($save_data);// this return bool
$user = User::insertGetId($save_data); // this returns nothing
})
Laravel 5.5.
Thanks
You can get the last inserted id by:
DB::getPdo()->lastInsertId();
// insert a user and get the record it
DB::transaction(function () {
$user = User::insert($save_data);
$lastID = DB::getPdo()->lastInsertId();
});
Alternatively, you can use the insertGetId method:
DB::transaction(function () {
$id = DB::table('users')->insertGetId($save_data);
});
Using Eloquent will return the id, as well:
DB::transaction(function () {
// using create
$user = User::create($save_data);
// $user->id
// or using save
$user = new User;
$user->foo = $save_data['foo'];
$user->save();
// $user->id;
});
Related
I Can't change the company app status Approved/Revoked, I tried to load and update the team_app entity using EntityTypeManager, and the other values have been updated without any issues like (callback URL, Description, Dispalyname, and custom attributes) but still the app status won't change/update,
$app_storage = \Drupal::entityTypeManager()->getStorage('team_app');
$app_ids = $app_storage->getQuery()
->condition('companyName', $team->id())
->condition('name', $app_mame)
->execute();
if (!empty($app_ids)) {
$app_id = reset($app_ids);
$loaded_app = $app_storage->load($app_id);
$loaded_app->set('status', 'revoked');
$loaded_app->save();
}
Also, I tried to make a PUT API request to change the app status with the same results, No status value changed.
/** #var \Drupal\apigee_edge\SDKConnectorInterface $sdk_connector */
$sdk_connector = \Drupal::service('apigee_edge.sdk_connector');
try {
$sdk_connector->testConnection();
$client = $sdk_connector->getClient();
}
catch (\Exception $exception) {
dump('client is not defined');
die();
}
$endpoint = $client->getUriFactory()
->createUri("/organizations/{$sdk_connector->getOrganization()}/companies/{$team->id()}/apps/{$loaded_app->getName()}");
try {
$response = $client->get($client->getEndpoint() . $endpoint);
$results = json_decode((string) $response->getBody());
$results->status = 'revoked';
// PUT.
$endpoint = $client->getUriFactory()
->createUri("/organizations/{$sdk_connector->getOrganization()}/companies/{$team->id()}/apps/{$loaded_app->getName()}")
$response = $client->put($client->getEndpoint() . $endpoint, json_encode($results));
$results = (array) json_decode((string) $response->getBody());
}
catch (\Exception $exception) {
dump('error, not trigger');
}
Any help with this?
I need to get sitecore information that collected from anonymous users to give him availability to export it or opt out - [GDPR]
any idea about contact ID for anonymous !
The way of doing it is dependent on the sitecore version.
Sitcore 9 you can use right to be forgotten
Sitecore 8+ you have to implement the feature from scratch.
Regarding Anonymous user - If the user is really anonymous, then you done need to worry about the GDPR (my view). But sometimes we map user email and sensitive personal info to anonymous user by using forms or WFFM. You can use email address of that user to query xDB (Contact Identifiers) to get the contact and contactID. Then reset informations.
Also: please note that based on WFFFM save action config, anonymous user will store in Core DB and Contact List.
To forget a user, you can use the following code. It will execute the ExecuteRightToBeForgotten function on the contact and scrub their data.
Forget User
public bool ForgetUser()
{
var id = _contactIdentificationRepository.GetContactId();
if (id == null)
{
return false;
}
var contactReference = new IdentifiedContactReference(id.Source, id.Identifier);
using (var client = _contactIdentificationRepository.CreateContext())
{
var contact = client.Get(contactReference, new ContactExpandOptions());
if (contact != null)
{
client.ExecuteRightToBeForgotten(contact);
client.Submit();
}
}
return false;
}
Fake up some data
public void FakeUserInfo()
{
var contactReference = _contactIdentificationRepository.GetContactReference();
using (var client = SitecoreXConnectClientConfiguration.GetClient())
{
// we can have 1 to many facets
// PersonalInformation.DefaultFacetKey
// EmailAddressList.DefaultFacetKey
// Avatar.DefaultFacetKey
// PhoneNumberList.DefaultFacetKey
// AddressList.DefaultFacetKey
// plus custom ones
var facets = new List<string> { PersonalInformation.DefaultFacetKey };
// get the contact
var contact = client.Get(contactReference, new ContactExpandOptions(facets.ToArray()));
// pull the facet from the contact (if it exists)
var facet = contact.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey);
// if it exists, change it, else make a new one
if (facet != null)
{
facet.FirstName = $"Myrtle-{DateTime.Now.Date.ToString(CultureInfo.InvariantCulture)}";
facet.LastName = $"McSitecore-{DateTime.Now.Date.ToString(CultureInfo.InvariantCulture)}";
// set the facet on the client connection
client.SetFacet(contact, PersonalInformation.DefaultFacetKey, facet);
}
else
{
// make a new one
var personalInfoFacet = new PersonalInformation()
{
FirstName = "Myrtle",
LastName = "McSitecore"
};
// set the facet on the client connection
client.SetFacet(contact, PersonalInformation.DefaultFacetKey, personalInfoFacet);
}
if (contact != null)
{
// submit the changes to xConnect
client.Submit();
// reset the contact
_contactIdentificationRepository.Manager.RemoveFromSession(Analytics.Tracker.Current.Contact.ContactId);
Analytics.Tracker.Current.Session.Contact = _contactIdentificationRepository.Manager.LoadContact(Analytics.Tracker.Current.Contact.ContactId);
}
}
}
ContactIdentificationRepository
using System.Linq;
using Sitecore.Analytics;
using Sitecore.Analytics.Model;
using Sitecore.Analytics.Tracking;
using Sitecore.Configuration;
using Sitecore.XConnect;
using Sitecore.XConnect.Client.Configuration;
namespace Sitecore.Foundation.Accounts.Repositories
{
public class ContactIdentificationRepository
{
private readonly ContactManager contactManager;
public ContactManager Manager => contactManager;
public ContactIdentificationRepository()
{
contactManager = Factory.CreateObject("tracking/contactManager", true) as ContactManager;
}
public IdentifiedContactReference GetContactReference()
{
// get the contact id from the current contact
var id = GetContactId();
// if the contact is new or has no identifiers
var anon = Tracker.Current.Contact.IsNew || Tracker.Current.Contact.Identifiers.Count == 0;
// if the user is anon, get the xD.Tracker identifier, else get the one we found
return anon
? new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N"))
: new IdentifiedContactReference(id.Source, id.Identifier);
}
public Analytics.Model.Entities.ContactIdentifier GetContactId()
{
if (Tracker.Current?.Contact == null)
{
return null;
}
if (Tracker.Current.Contact.IsNew)
{
// write the contact to xConnect so we can work with it
this.SaveContact();
}
return Tracker.Current.Contact.Identifiers.FirstOrDefault();
}
public void SaveContact()
{
// we need the contract to be saved to xConnect. It is only in session now
Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
this.contactManager.SaveContactToCollectionDb(Tracker.Current.Contact);
}
public IXdbContext CreateContext()
{
return SitecoreXConnectClientConfiguration.GetClient();
}
}
}
How to get anonymous contact ID using Sitecore API?
I'm using this code but can't find the contact ID in xconnect DB.
using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
// var enumerator = client.Interactions.Where(x => x.DeviceProfile.Id == contactId).GetBatchEnumeratorSync(10);
Event ev = new Event(Guid.NewGuid(), DateTime.UtcNow) { Duration = new TimeSpan(20) };
var reference = new ContactReference(contactId);
Contact contact = client.Get<Contact>(reference, new ContactExpandOptions() { });
if (contact != null)
{
client.ExecuteRightToBeForgotten(contact);
client.Submit();
}
}
catch (XdbExecutionException ex)
{
// Manage exceptions
}
}
You can get it with the code new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N")) This is the xDB identifier which is the identifier anonymous contacts get.
Here is the code I use _contactIdentificationRepository is in a Foundation repository. _contactIdentificationRepository.GetContactReference() will get the anonymous or identified contact reference.
Call xConnect
var contactReference = _contactIdentificationRepository.GetContactReference();
using (var client = SitecoreXConnectClientConfiguration.GetClient())
{
// we can have 1 to many facets
// PersonalInformation.DefaultFacetKey
// EmailAddressList.DefaultFacetKey
// Avatar.DefaultFacetKey
// PhoneNumberList.DefaultFacetKey
// AddressList.DefaultFacetKey
// plus custom ones
var facets = new List<string> { PersonalInformation.DefaultFacetKey };
// get the contact
var contact = client.Get(contactReference, new ContactExpandOptions(facets.ToArray()));
.....
}
_contactIdentificationRepository
private readonly ContactManager contactManager;
public ContactManager Manager => contactManager;
public ContactIdentificationRepository()
{
contactManager = Factory.CreateObject("tracking/contactManager", true) as ContactManager;
}
public IdentifiedContactReference GetContactReference()
{
// get the contact id from the current contact
var id = GetContactId();
// if the contact is new or has no identifiers
var anon = Tracker.Current.Contact.IsNew || Tracker.Current.Contact.Identifiers.Count == 0;
// if the user is anon, get the xD.Tracker identifier, else get the one we found
return anon
? new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N"))
: new IdentifiedContactReference(id.Source, id.Identifier);
}
public Analytics.Model.Entities.ContactIdentifier GetContactId()
{
if (Tracker.Current?.Contact == null)
{
return null;
}
if (Tracker.Current.Contact.IsNew)
{
// write the contact to xConnect so we can work with it
this.SaveContact();
}
return Tracker.Current.Contact.Identifiers.FirstOrDefault();
}
public void SaveContact()
{
// we need the contract to be saved to xConnect. It is only in session now
Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
this.contactManager.SaveContactToCollectionDb(Tracker.Current.Contact);
}
i am writing webservice in symfony2 but i facing some problem regarding the output ,as it is giving blank output.
class DefaultController extends Controller {
/**
*
* #Route("/webservices/activity/{id}", name="user_json_activity")
* #Method("get")
*/
public function activityAction($id) {
$em = $this->getDoctrine()->getEntityManager();
$list = $em->getRepository('FitugowebserviceBundle:activity')->findOneById($id);
$r_array = $this->routes2Array($list);
$r = array('activity' => $r_array);
return new Response(json_encode($r));
}
private function routes2Array($routes) {
$points_array = array();
foreach ($routes as $route) {
$r_array = array('activity' => $route->getActivity(),
'icon' => $route->getIcon());
$points_array[] = $r_array;
}
return $points_array;
}
}
When i try to fetch data for id=1 http://domain.org/fitugo/web/app_dev.php/webservices/activity/1 it is giving output as follows
{"activity":[]}
It look very strange that you want get array with findOneById method. The first thing I suggest to add a check that the entity founded by id exist. Then look that findOneById returns and check your controller logic.
If I try to create a record with something like
var myObject = App.ModelName.createRecord( data );
myObject.get("transaction").commit();
the id of myObject is never set.
This says that id generation should be handled by EmberData (first response). So what should be happening? Where is the new id determined. Shouldn't there be a callback to the API to get valid id?
ID is the primary key for your record which is created by your database, not by Ember. This is JSON structure submit to REST post, notice no ID.
{"post":{"title":"c","author":"c","body":"c"}}
At your REST Post function you must get the last insert ID and return it back with the rest of the model data to Ember using this following JSON structure. Notice the ID, that is the last insert ID. You must get that last insert ID manually using your DB api.
{"post":{"id":"20","title":"c","author":"c","body":"c"}}
This is my sample code for my REST post. I coded this using PHP REST Slim framework:
$app->post('/posts', 'addPost'); //insert new post
function addPost() {
$request = \Slim\Slim::getInstance()->request();
$data = json_decode($request->getBody());
//logging json data received from Ember!
$file = 'json1.txt';
file_put_contents($file, json_encode($data));
//exit;
foreach($data as $key => $value) {
$postData = $value;
}
$post = new Post();
foreach($postData as $key => $value) {
if ($key == "title")
$post->title = $value;
if ($key == "author")
$post->author = $value;
if ($key == "body")
$post->body = $value;
}
//logging
$file = 'json2.txt';
file_put_contents($file, json_encode($post));
$sql = "INSERT INTO posts (title, author, body) VALUES (:title, :author, :body)";
try
{
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("title", $post->title);
$stmt->bindParam("author", $post->author);
$stmt->bindParam("body", $post->body);
$stmt->execute();
$insertID = $db->lastInsertId(); //get the last insert ID
$post->id = $insertID;
//prepare the Ember Json structure
$emberJson = array("post" => $post);
//logging
$file = 'json3.txt';
file_put_contents($file, json_encode($emberJson));
//return the new model back to Ember for model update
echo json_encode($emberJson);
}
catch(PDOException $e)
{
//$errorMessage = $e->getMessage();
//$data = Array(
// "insertStatus" => "failed",
// "errorMessage" => $errorMessage
//);
}
}
With some REST adapters, such as Firebase, you can define the id as a variable of the record you are going to create.
App.User = DS.Model.extend({
firstName: DS.attr('string')
});
var sampleUser = model.store.createRecord('user', {
id: '4231341234891234',
firstName: 'andreas'
});
sampleUser.save();
JSON in the database (Firebase)
"users": {
"4231341234891234": {
"firstName": "andreas"
}
}