bulk remove the required paramater fron custom option magento - database

i have around 10000 products in my database which all have custom options and they all are set to required.
I need to unset required.
Please suggest me how can i do this dynamically.
I don't want to do it one by one from magento admin because that will take forever
thanks

If you want to reset the required field for all custom options of all products here is a quick & dirty way of doing it.
All the custom options are stored in the table catalog_product_option.
The column name that decides if the option is required or not is is_require.
So running this query should do the trick.
UPDATE `catalog_product_option` SET `is_require` = 0 WHERE 1
Add the table prefix if you have one.

you can update those product's required parameter by using import product by csv. I think, you have imported products by csv. simply copy that SKU and custom field option into new csv file.
And import Again those products. It will update custom option required field as you want

I'm just expanding on Marius' answer. I needed to do this but only for a bunch of custom options I'd made required by accident. I figure it might help someone else who made a similar miscalculation! :-D
UPDATE catalog_product_option o
JOIN catalog_product_option_title t ON t.option_id=o.option_id
SET o.is_require = 0
WHERE t.title = 'Additional Comments'
AND o.is_require = 1
Luckily the options I imported all had the same title so I was able to filter it that way.
If you're using SKU's for your custom options, you could probably further simplify the query as it requires no joins.
UPDATE catalog_product_option o
SET o.is_require = 0
WHERE o.sku = 'SKU1234'
AND o.is_require = 1
^ not tested that but looking at the structure of the table that should work.

Related

Query of Arrays in Salesforce

I need to do 1 of two things (I believe):
1- Get a Custom Object ID so I can query it directly
2- Get a list of values of a specific field within the Object entries.
Ultimate End goal:
Add and modify rows in my custom object via external API. However to do this I need to check and make sure my new entry/row does not already exist.
What I have:
I have a custom object (called Customer_Arrays__c). It is a table that I can add new rows to (I will call entrys). Each entry has 6 or 7 fields. 1 of these fields is called (external_ID__c). This is the field I utilize to match to new incoming data to see if the entry already exists, or if it needs to add a new row to my table. This Customer_Arrays__c is a child to my opportunity I believe – it is part of every opportunity and each line item I add has a field defaulted to the opportunity.
Help I need:
1- How do I query the value of my Cutomer_Arrays__c based upon an opportunity ID?
2- How do I query a list of values in my (external_ID__c) based upon an opportunity ID?
Thanks for your help! I have read half a dozen+ posts on similar topics and am missing something. Examples of some Past try's that failed:
Select external_ID__c,FROM Custom_Arrays__c WHERE Opportunity='00...'
Select Id (Select ID, Custom_Arrays__c from Custom_Arrays__c) from Opportunity where id ='00...'
List FROM Custom_Arrays__c WHERE Opportunity='00...'
Select Id, external_ID__c, (Select external_ID__c FROM Custom_Arrays__c) WHERE Opportunity__c='00...'
Thanks again!
Only you know how did you name the lookup field (foreign key) from arrays to Opportunity. You'll need to check in setup, next to where external_ID__c is. Since it's a custom field (gets __c at the end), my guess is you went with default.
Try
SELECT Id, Name, External_Id__c
FROM Customer_Arrays__c
WHERE Opportunity__c = '006...'
Thank you eyescream, that got me almost all the way there. Turns out I also needed a __r for the parent child relationship.
Here is a snip out of my final code that works - I think it covers everything:
SELECT Field1__c, Opportunity__r.Id, Opportunity__r.Opportunity__c,
FROM Customer_Arrays__c
WHERE Opportunity__r.Id = '006...'.
Thank you so very much!!!

Sitecore > Update commerce index incrementally

I am trying to rebuild commerce index in Sitecore incrementally(so, I don't want to make a full rebuild). Index strategy is set to "manual" at the moment.
I made some changes in catalog(updated relations and data, added/removed products and categories) and now just want to update index correspondingly.
I am tried to use class IndexCustodian(read about this class in the article). However, can't find the detailed documentation for this class with some code examples.
For example, I tried to use IncrementalUpdate method. As a second parameter I used an array of IndexableUniqueId(created on a search result using uniqueid field), but index hasn't been changed.
IEnumerable<IIndexableUniqueId> uniqueIds = foundProducts.Select(x => new IndexableUniqueId<string>(x.UniqueId));
Job job = IndexCustodian.IncrementalUpdate(ContentSearchManager.GetIndex(indexName), uniqueIds);
Another example, I tried to use Refresh method. As a second input parameter I used object of type CommerceIndexableItem which was created for the root sitecore item of my catalog. New products have been added, but existing product has been updated not completely: category relation has been updated, localized string field - hasn't been updated. Removed from catalog products still presented in the index.
Database database = Database.GetDatabase("web");
Item rootFolder = database.GetItem(Paths.DefaultCatalogPath);
CommerceIndexableItem indexableFolder = new CommerceIndexableItem(rootFolder);
Job job = IndexCustodian.Refresh(ContentSearchManager.GetIndex(indexName), indexableFolder);
Will appreciate any example of using of IndexCustodian or any other way which allows to update the index.
Thank you in advance for the help.

How to set value in a field by UI?

I use three fields in Sqlserver Datavbase tables, for prevent delete records permanently by user:
IsDelete (bit)
DeletedDate (DateTime)
DeletedUserID (bigint)
I wish to set third field (DeletedUserID) by UI by some thing like this:
this.ExamdbDataSet.AcceptChanges();
DataRowView row = (DataRowView)this.BindingSource.Current;
row.BeginEdit();
row["DeletedUserID"] = User.User.Current.ID;
row.EndEdit();
this.ExamdbDataSet.AcceptChanges();
row.Delete();
and other two fields ,'IsDeleted' field and 'DeletedDate' are set automatically in table's 'After Delete Trigger'.
then commit changes to database with desire command successfuly with this code:
this.TableAdapterManager.UpdateAll(this.ExamdbDataSet);
but problem is , the 'DeletedUserID' is null in database.
and Question is : How to set 'DeletedUserID' field value by true way in UI?
I don't think it is a good way to do that. You have sliced a simple logic to separate parts, each being done in a different part of the application (UI, Trigger, ...). You set value of some field, and then DELETE the whole record! Don't expect anything else that the current situation.
You would better set all fields in UI (i.e. no trigger in this case), and change the query that loads data. For example,
Select * from table1 where IsDeleted=0
You didn't tell us anything about whether your use ASP.Net or WinForms. Give us more info.

Salesforce Junction Objects

To all salesforce experts i need some assistance. I have my contacts and a custom object named programs. I created a junction object using to master detail relationships with contacts and programs. I want to avoid relating the same contact to the same program. I tried triggers but I couldn't create the testing part to use it outside sandbox.
I went back to the basics and created a Unique text field. I tried to use default value but EVERYTHING i write in that crap is wrong -_-. I tried Contact__r.Email & "-" & Program__r.Name but to no avail.
I tried workflow rules with a field update but my field update NEVER runs.(Yes I did activate the workflow rule) and I didn't know what to write in my rule's code.
The workflow firing condition could be simply a formula that says true. Alternatively use "every time record is inserted". It also depends whether your master-details are set once and that's it or they will be "reparentable" (option introduced in Summer '12 I think). Maybe post a screenshot / text description of your firing condition? Also - is your unique field set to "case sensitive"?
As for the formula to populate the unique field - something like Contact__c + ' ' + Program__c (or whatever the API names of your fields are) should be OK. Don't use Contact__r.Email etc as these don't have to be unique...
You'll have to somehow fill in the uniqueness criteria for all existing records (maybe that's why you claimed it doesn't work?). If you can use Apex for data fixes - something like this should get you started.
List<Junction__c> junctions = [SELECT Contact__c, Program__c
FROM Junction__c
WHERE Unique_Text_Field__c = null
LIMIT 10000];
for(Junction__c j : junctions){
String key = String.valueOf(j.Contact__c).left(15) + ' ' + String.valueOf(j.Program__c).left(15);
j.Unique_Text_Field__c = key;
}
update junctions;
Keep rerunning it until it starts to show 0 rows processed. The Ids are cut down to 15 chars because in Apex you'd usually see full 18-char Id but workflows use 15-char versions.

Adding a projection to an NHibernate criteria stops it from performing default entity selection

I'm writing an NHibernate criteria that selects data supporting paging. I'm using the COUNT(*) OVER() expression from SQL Server 2005(+) to get hold of the total number of available rows, as suggested by Ayende Rahien. I need that number to be able to calculate how many pages there are in total. The beauty of this solution is that I don't need to execute a second query to get hold of the row count.
However, I can't seem to manage to write a working criteria (Ayende only provides an HQL query).
Here's an SQL query that shows what I want and it works just fine. Note that I intentionally left out the actual paging logic to focus on the problem:
SELECT Items.*, COUNT(*) OVER() AS rowcount
FROM Items
Here's the HQL:
select
item, rowcount()
from
Item item
Note that the rowcount() function is registered in a custom NHibernate dialect and resolves to COUNT(*) OVER() in SQL.
A requirement is that the query is expressed using a criteria. Unfortunately, I don't know how to get it right:
var query = Session
.CreateCriteria<Item>("item")
.SetProjection(
Projections.SqlFunction("rowcount", NHibernateUtil.Int32));
Whenever I add a projection, NHibernate doesn't select item (like it would without a projection), just the rowcount() while I really need both. Also, I can't seem to project item as a whole, only it's properties and I really don't want to list all of them.
I hope someone has a solution to this. Thanks anyway.
I think it is not possible in Criteria, it has some limits.
You could get the id and load items in a subsequent query:
var query = Session
.CreateCriteria<Item>("item")
.SetProjection(Projections.ProjectionList()
.Add(Projections.SqlFunction("rowcount", NHibernateUtil.Int32))
.Add(Projections.Id()));
If you don't like it, use HQL, you can set the maximal number of results there too:
IList<Item> result = Session
.CreateQuery("select item, rowcount() from item where ..." )
.SetMaxResult(100)
.List<Item>();
Use CreateMultiCriteria.
You can execute 2 simple statements with only one hit to the DB that way.
I am wondering why using Criteria is a requirement. Can't you use session.CreateSQLQuery? If you really must do it in one query, I would have suggested pulling back the Item objects and the count, like:
select {item.*}, count(*) over()
from Item {item}
...this way you can get back Item objects from your query, along with the count. If you experience a problem with Hibernate's caching, you can also configure the query spaces (entity/table caches) associated with a native query so that stale query cache entries will be cleared automatically.
If I understand your question properly, I have a solution. I struggled quite a bit with this same problem.
Let me quickly describe the problem I had, to make sure we're on the same page. My problem came down to paging. I want to display 10 records in the UI, but I also want to know the total number of records that matched the filter criteria. I wanted to accomplish this using the NH criteria API, but when adding a projection for row count, my query no longer worked, and I wouldn't get any results (I don't remember the specific error, but it sounds like what you're getting).
Here's my solution (copy & paste from my current production code). Note that "SessionError" is the name of the business entity I'm retrieving paged data for, according to 3 filter criterion: IsDev, IsRead, and IsResolved.
ICriteria crit = CurrentSession.CreateCriteria(typeof (SessionError))
.Add(Restrictions.Eq("WebApp", this));
if (isDev.HasValue)
crit.Add(Restrictions.Eq("IsDev", isDev.Value));
if (isRead.HasValue)
crit.Add(Restrictions.Eq("IsRead", isRead.Value));
if (isResolved.HasValue)
crit.Add(Restrictions.Eq("IsResolved", isResolved.Value));
// Order by most recent
crit.AddOrder(Order.Desc("DateCreated"));
// Copy the ICriteria query to get a row count as well
ICriteria critCount = CriteriaTransformer.Clone(crit)
.SetProjection(Projections.RowCountInt64());
critCount.Orders.Clear();
// NOW add the paging vars to the original query
crit = crit
.SetMaxResults(pageSize)
.SetFirstResult(pageNum_oneBased * pageSize);
// Set up a multi criteria to get your data in a single trip to the database
IMultiCriteria multCrit = CurrentSession.CreateMultiCriteria()
.Add(crit)
.Add(critCount);
// Get the results
IList results = multCrit.List();
List<SessionError> sessionErrors = new List<SessionError>();
foreach (SessionError sessErr in ((IList)results[0]))
sessionErrors.Add(sessErr);
numResults = (long)((IList)results[1])[0];
So I create my base criteria, with optional restrictions. Then I CLONE it, and add a row count projection to the CLONED criteria. Note that I clone it before I add the paging restrictions. Then I set up an IMultiCriteria to contain the original and cloned ICriteria objects, and use the IMultiCriteria to execute both of them. Now I have my paged data from the original ICriteria (and I only dragged the data I need across the wire), and also a raw count of how many actual records matched my criteria (useful for display or creating paging links, or whatever). This strategy has worked well for me. I hope this is helpful.
I would suggest investigating custom result transformer by calling SetResultTransformer() on your session.
Create a formula property in the class mapping:
<property name="TotalRecords" formula="count(*) over()" type="Int32" not-null="true"/>;
IList<...> result = criteria.SetFirstResult(skip).SetMaxResults(take).List<...>();
totalRecords = (result != null && result.Count > 0) ? result[0].TotalRecords : 0;
return result;

Resources