How to create Prestashop product with custom attributes programatically? - module

Maybe some of you who uses prestashop core classes know how to create product with custom attributes? I mean add new product in prestashop system by creating script that uses prestashop class for this purpose programatically.

#Santo Boldižar
His code working fine.if you create new attribute programmatically use below code to add a new attribute and get $idProductAttribute
use PrestaShop\PrestaShop\Adapter\Import\ImportDataFormatter;
$newGroup = new AttributeGroup();
$newGroup->name = ImportDataFormatter::createMultiLangField('test');
$newGroup->public_name = ImportDataFormatter::createMultiLangField('test');
$newGroup->group_type = 'select';
$newGroup->add();
$newAttribute = new Attribute();
$newAttribute->name = ImportDataFormatter::createMultiLangField('test');
$newAttribute->id_attribute_group = $newGroup->id;
$newAttribute->add();
$idProductAttribute = $product->addProductAttribute($price,
$weight,
$unit_impact,
$ecotax,
$quantity,
$id_images,
$reference,
$id_supplier,
$ean13,
$default,
$location,
$upc,
$minimal_quantity,
$isbn,
$low_stock_threshold,
$low_stock_alert);
$product->addAttributeCombinaison($idProductAttribute, array($newAttribute->id_attribute_group));
This is working for me.

I created products with attributes in PrestaShop 1.7.5, here a part of my code.
First load the product:
$product = new \Product($productId);
Then, add an attribute to this product:
// The $data array contains all of the required data for an attribute.
$idProductAttribute = $product->addProductAttribute(
(float)$data['price'], // Product price (+/-) - If the base product price is 50 and you set here -5, the new price will be 45
(float)$data['weight'], // Product weight
$data['unit_impact'],
$data['ecotax'],
(int)$data['quantity'], // Products available in stock
$data['id_images'], // Image ids
$data['reference'],
strval($data['suppliers']),
strval($data['ean13']), // Barcode
$data['default'], // Default product or not (1/0)
$data['location'],
$data['upc'],
$data['minimal_quantity'], // Default 1
$data['isbn']
);
$product->addAttributeCombinaison($idProductAttribute, $data['attribute_ids']); // $data['attribute_ids'] - id(s) of existing attribute(s).
And voilá, you have a product with a new attribute.

Related

Send 'Comment' or additional field with Global Payments HPP - PHP SDK - RXP JS

How do you send additional data through to Global Payments like 'Comment', 'CustomerNumber' or 'ProductId' using the HPP with PHP SDK / RXP JS?
I have tried the following and cannot see any documentation for it.
// Add 3D Secure 2 Mandatory and Recommended Fields
$hostedPaymentData = new HostedPaymentData();
$hostedPaymentData->customerName = 'Your name';
$hostedPaymentData->customerEmail = 'email#email.com';
// not working
$hostedPaymentData->customerNumber = '48898984';
$hostedPaymentData->productId = '48898984';
$hostedPaymentData->comment1 = '48898984';

Django how to maintain a session?

I'm developing an e-commerce site and I'm working on the shopping cart functionality. When the user is not connected I create a session for him so that he can add products to the basket which is normal, when the user decides to place this order I ask him to connect but when he connects he loses the session that I had created for him and another session is assigned to him. The cause is that once connected it loses all its products selected in the screen. After reading the documentation on django sessions I found nothing that could help me.
here is my code for more details:
models.py
class Cart(models.Model):
session_id = models.CharField(max_length=150)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=0, validators=[MinValueValidator(1)])
updated = models.fields.DateTimeField(auto_now=True)
created = models.fields.DateTimeField(auto_now_add=True)
deleted = models.fields.BooleanField(default=False)
def __str__(self) -> str:
return str(self.product)
views.py
class FrontProductAddCart(View):
def post(self, request, product_pk):
session_id = request.session._get_or_create_session_key()
product = models.Products.objects.get(pk=product_pk)
objet, create = models.Cart.objects.get_or_create(session_id=session_id, product=product)
quantity = request.POST.get("quantity")
if quantity:
objet.quantity = quantity
objet.save()
else:
objet.quantity += 1
objet.save()
return HttpResponse(
"",
headers={
"HX-Trigger": json.dumps({
"product_add_cart": context_processors.get_total_number_products(request)
})
}
)

Programmatically Creating Attributes - Prestashop 1.6

I am programmatically adding attributes to Prestashop 1.6 as follows:
$newGroup = new AttributeGroup();
$newGroup->name = $this->createMultiLangField('test');
$newGroup->public_name = $this->createMultiLangField('test');
$newGroup->group_type = 'select';
$newGroup->add();
$newAttribute = new Attribute();
$newAttribute->name = $this->createMultiLangField('test');
$newAttribute->id_attribute_group = $newGroup->id;
$newAttribute->add();
When I look in my catalog this attribute and its group are there and everything appears to be in order. However, when I click combinations on any of my products after doing this, the ajax loader spins out indefinately (I can no longer create combinations on ANY of my products). Has anybody experienced anything like this?
The code should be:
$newGroup = new AttributeGroup();
$newGroup->name = $this->createMultiLangField('test');
$newGroup->public_name = $this->createMultiLangField('test');
$newGroup->group_type = 'select';
$newGroup->add();
$newAttribute = new Attribute();
$newAttribute->name = $this->createMultiLangField('test');
$newAttribute->id_attribute_group = $newGroup->id;
$newAttribute->add();

Update a DynamicContent item of a dynamic module in Sitefinity

I am trying to update a DynamicContent Property of a module using the following:
DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager();
Type pollanswerType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Poll.Pollanswer");
Guid pollanswerID = new Guid(answerID);
// This is how we get the pollanswer item by ID
DynamicContent pollanswerItem = dynamicModuleManager.GetDataItem(pollanswerType, pollanswerID);
pollanswerItem.SetValue("VoteCount", int.Parse(pollanswerItem.GetValue("VoteCount").ToString()) + 1);
dynamicModuleManager.SaveChanges();
Basically getting the current Property value and incrementing it by 1
and calling SaveChanges()
the code runs without errors but it doesn't update the value when I check it from the Back End of Sitefinity.
Any suggestions?
The problem might be caused by the pollanswerID that you are passing.
If the pollanswerID is the id of the live version of the content item then the value wouldn't be set.
Make sure you set the field value to the of master version of the content type not the live one.
In case you don't know the id of the master version of the content type you can get the master content item by the id of the live version of the content type
var masterItem = dynamicModuleManager.GetDataItems(pollanswerType).Where(dynItem => dynItem.Id == pollanswerItem.OriginalContentId).FirstOrDefault();
if (masterItem != null)
{
masterItem.SetValue("VoteCount", int.Parse(masterItem.GetValue("VoteCount").ToString()) + 5);
}
you should be always doing this
Get Master
Checkout Master
Checkin Master
Save Changes
Publish changes – this will update live.
bookingItemLive is the live record
var bookingItemMaster = dynamicModuleManager.Lifecycle.Edit(bookingItemLive) as DynamicContent;
//Check out the master to get a temp version.
DynamicContent bookingItemTemp = dynamicModuleManager.Lifecycle.CheckOut(bookingItemMaster) as DynamicContent;
//Make the modifications to the temp version.
bookingItemTemp.SetValue("CleanerId", cleanerId);
bookingItemTemp.SetValue("SubCleanerId", subCleanerId);
bookingItemTemp.LastModified = DateTime.UtcNow;
//Checkin the temp and get the updated master version.
//After the check in the temp version is deleted.
bookingItemMaster = dynamicModuleManager.Lifecycle.CheckIn(bookingItemTemp) as DynamicContent;
dynamicModuleManager.SaveChanges();
//Publish the item now
ILifecycleDataItem publishedBookingItem = dynamicModuleManager.Lifecycle.Publish(bookingItemMaster);
bookingItemMaster.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Published");
#Joseph Ghassan: You can follow below step.
Step 1: Get Live
var bookingItemLive= manager.GetDataItem(ModuleType, GuidId);
Step 2: Get Master
var bookingItemMaster = manager.Lifecycle.GetMaster(bookingItemLive) as DynamicContent;
Step 2: Checkout Master --> will be created a draft item( you will update data by draft)
if (bookingItemMaster == null)
{
return new HttpResponseMessage
{
Content = new JsonContent(new { Result = false })
};
}
var bookingItemDraff = manager.Lifecycle.CheckOut(bookingItemMaster) as DynamicContent;
//Make the modifications to the temp version.
bookingItemDraff.SetValue("CleanerId", cleanerId);
bookingItemDraff.SetValue("SubCleanerId", subCleanerId);
bookingItemDraff.LastModified = DateTime.UtcNow;
Step 3: Checkin Master
// Now we need to check in, so the changes apply
var checkInItem = manager.Lifecycle.CheckIn(bookingItemDraff);
Step 4: Publish changes
manager.Lifecycle.Publish(checkInItem);
Step 5: Save Changes - this will save to Database and update live.
bookingItemDraff.SetWorkflowStatus(manager.Provider.ApplicationName, CustomFieldName.PublishedStatus);
manager.SaveChanges();

How to add extra data to a member in MDS?

I'm running MDS on a virtual machine and trying to access the service from my host OS.
I've been able to add something to the database but my data is all over the place and in the Master Data Manager (website) I don't see the new member.
I suppose I shouldn't be using Attributes but something else but what and how? Are there tutorials because I can't find any ...?
Here's the code I'm using:
International international = new International();
EntityMembers entityMembers = new EntityMembers();
// Set the modelId, versionId, and entityId.
entityMembers.ModelId = new Identifier { Name = modelName };
entityMembers.VersionId = new Identifier { Name = versionName };
entityMembers.EntityId = new Identifier { Name = entityName };
entityMembers.MemberType = memberType;
Collection<Member> members = new Collection<Member>();
Member aNewMember = new Member();
aNewMember.MemberId = new MemberIdentifier() { Name = employee.FullName, Code = aNewCode, MemberType = memberType };
Collection<MDS.Attribute> attributes = new Collection<MDS.Attribute>();
MDS.Attribute attrOrgUnit = new MDS.Attribute();
attrOrgUnit.Identifier = new Identifier() { Name = "OrganizationalUnit" };
attrOrgUnit.Value = employee.OrganizationalUnit;
attrOrgUnit.Type = AttributeValueType.String;
attributes.Add(attrOrgUnit);
aNewMember.Attributes = attributes.ToArray();
members.Add(aNewMember);
entityMembers.Members = members.ToArray();
// Create a new entity member
OperationResult operationResult = new OperationResult();
clientProxy.EntityMembersCreate(international, entityMembers, false, out operationResult);
HandleOperationErrors(operationResult);
I have been able to fix my own problem.
First of all: creating separate variables with collections and converting them to arrays afterwards is not necessary. The code from the tutorials works but fails to mention that, when adding the service reference, you have to configure it (right-click on the service reference -> configure) to use Collections as "Collection type" instead of arrays and to generate message contracts.
Second, the code above with the attributes is correct and works perfectly. The problem I had which failed to add messages with attributes was unrelated. It was a connection/authentication problem between my Host OS and Guest OS.
Hope this helps someone.