ajax function total_selection disable or enable import - ajax

Below is function code:
if(total_selection == 8)
{
$('#import').attr('disabled', false);
product_type = column_data.product_type;
sku = column_data.sku;
category_id = column_data.category_id;
price = column_data.price;
currency = column_data.currency;
discount_rate = column_data.discount_rate;
vat_rate = column_data.vat_rate;
stock = column_data.stock;
}
else
{
$('#import').attr('disabled', 'disabled');
}
This function enable button import
if(total_selection == 8)
How to change example if total_selection 3 or more then enable import button and set
price = column_data.price; sku = column_data.sku; stock = column_data.stock;
as required?

Related

Validate a dynamically generated CheckBox

I'm generating an asp:CheckBox dynamically and I need to validate that it is checked with a CustomValidator().
private void AddCheckBox(HtmlGenericControl newDiv, AdditionalFields field)
{
var additionalFieldDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
additionalFieldDiv.Attributes.Add("class", "additional-field-row");
var additionalLabel = new RadLabel();
additionalLabel.Text = field.Label;
additionalLabel.ID = "AdditionalLabel" + field.ControlId;
additionalLabel.CssClass += "title ";
additionalLabel.Width = new Unit(field.LabelWidth ?? 175);
if (field.Required??false) additionalLabel.CssClass += "additional-field-required";
var additionalField = new System.Web.UI.WebControls.CheckBox();
additionalField.ID = "AdditionalField" + field.ControlId;
additionalField.CssClass += "additional-field-checkbox";
additionalField.Width = new Unit(field.Width ?? 200);
var customValidator = new CustomValidator();
customValidator.ID = "CustomValidator" + field.ControlId;
//customValidator.ClientValidationFunction = "CheckBoxValidation(AdditionalField"+ field.ControlId +")";
customValidator.ControlToValidate = "AdditionalField" + field.ControlId;
customValidator.ErrorMessage = string.IsNullOrEmpty(field.ErrorMessage) ? field.Label + " required" : field.ErrorMessage;
customValidator.CssClass += "additional-fields-validator";
customValidator.Display = ValidatorDisplay.Dynamic;
customValidator.ValidationGroup = "valGroup";
customValidator.EnableClientScript = true;
newDiv.Controls.Add(additionalFieldDiv);
additionalFieldDiv.Controls.Add(additionalLabel);
additionalFieldDiv.Controls.Add(additionalField);
if (field.Required ?? false)
{
additionalFieldDiv.Controls.Add(customValidator);
}
}
I get an error if I try to use customValidator.ControlToValidate = "AdditionalField" + field.ControlId;
Control 'AdditionalField9' referenced by the ControlToValidate property of 'CustomValidator9' cannot be validated.
I have several other controls on the page that are in the validation group "valGroup" and I like the CheckBox validated client side. If I can't use the ControlToValidate property do I need to use JavaScript, and if so how do I pass the ID of the CheckBox to validate?
<script type = "text/javascript">
function ValidateCheckBox(sender, args) {
if (document.getElementById("<%=AdditionalField9.ClientID %>").checked == true) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
</script>
Hope you can help

Dynamics crm + plugin logic to update zero values

I need to perform the sum of each field across multiple records of the same entity and update the values on the same entity. Along with this I also need to store its formula.
AttributeList = { "price ", "quantity", "contact.revenue", "opportunity.sales"}
Below is the logic
foreach (var attribute in attributeList)
{
Decimal fieldSum = 0;
string computedNote = string.Empty;
foreach (var entity in mainEntityList)
{
if (entity.Contains(attribute))
{
if (entity.Attributes[attribute] != null)
{
string type = entity.Attributes[attribute].GetType().Name;
Decimal attrValue = 0;
if (type == "AliasedValue")
{
AliasedValue aliasedFieldValue = (entity.GetAttributeValue<AliasedValue>(attribute));
attrValue = aliasedFieldValue.Value.GetType().Name == "Decimal" ? (Decimal)aliasedFieldValue.Value : (Int32)aliasedFieldValue.Value;
}
else
{
attrValue = entity.Attributes[attribute].GetType().Name == "Decimal" ? entity.GetAttributeValue<Decimal>(attribute) : entity.GetAttributeValue<Int32>(attribute);
}
fieldSum += attrValue;
computedNote += $"+{Convert.ToInt32(attrValue).ToString()}";
}
}
else
{
computedNote += $"+0";
}
}
Entity formula = new Entity("formula");
if (fieldSum != 0)
{
if (attribute.Contains("opportunity"))
{
opportunity[attributeName] = fieldSum;
entityName = Opportunity.EntityLogicalName;
attributeName = attribute;
recordId = Id;
}
else if (attribute.Contains("contact"))
{
contact[attributeName] = fieldSum;
entityName = Contact.EntityLogicalName;
attributeName = attribute;
recordId = Id;
}
else
{
mainentity[attribute] = fieldSum;
entityName = mainEntity.EntityLogicalName;
attributeName = attribute;
recordId = Id;
}
formula.Attributes["ice_entity"] = entityName;
formula.Attributes["ice_attribute"] = attributeName;
formula.Attributes[entityName + "id"] = new EntityReference(entityName, recordId);
formula.Attributes["ice_computednote"] = computedNote.Remove(0, 1);
requestsCollection.Entities.Add(formula);
}
}
requestsCollection.Entities.Add(opportunity);
requestsCollection.Entities.Add(contact);
requestsCollection.Entities.Add(mainentity);
Values in both records could be as follows
Record 1
Price = 500
Quantity = 25
Revenue = 100
Sales = 10000
Volume = 0
Record 2
Price = 200
Quantity = 10
Revenue = 100
Sales = -10000
Volume = 0
Record 3 (Values after calculation that are to be updated in the third entity and Formula to be stored mentioned in brackets)
Price = 700 Formula = (500+200)
Quantity = 35 Formula = (25+10)
Revenue = 200 Formula =(100+100)
Sales = 0 Formula =(10000 + (-10000))
Volume = 0 No Formula to be created
I am checking if the fieldsum is not equal to zero (to update both positive and negative values) and then updating the values in the respective entity. However for values that became zero after the calculation. I also need to update them and create formula for the same. Avoiding the values that were zero by default.
As shown in above example, I want to update sales field value and create formula record for the same as '10000+-10000' but do not want volume field value to be updated or the formula to be created for it. How can i embed this logic in my code?
Add a flag (updateFormula) to indicate whether checksum and formula required to update in related entities. Then, instead of checking fieldSum != 0, check updateFormula is true to update the related records.
attributeList = { "price", "quantity", "contact.revenue", "opportunity.sales"}
foreach (var attribute in attributeList)
{
Decimal fieldSum = 0;
string computedNote = string.Empty;
bool updateFormula = false;
foreach (var entity in mainEntityList)
{
if (entity.Contains(attribute))
{
if (entity.Attributes[attribute] != null)
{
string type = entity.Attributes[attribute].GetType().Name;
Decimal attrValue = 0;
if (type == "AliasedValue")
{
AliasedValue aliasedFieldValue = (entity.GetAttributeValue<AliasedValue>(attribute));
attrValue = aliasedFieldValue.Value.GetType().Name == "Decimal" ? (Decimal)aliasedFieldValue.Value : (Int32)aliasedFieldValue.Value;
}
else
{
attrValue = entity.Attributes[attribute].GetType().Name == "Decimal" ? entity.GetAttributeValue<Decimal>(attribute) : entity.GetAttributeValue<Int32>(attribute);
}
fieldSum += attrValue;
computedNote += Convert.ToInt32(attrValue).ToString();
updateFormula = true;
}
}
else
{
computedNote += 0;
}
}
Entity formula = new Entity("formula");
if (updateFormula)
{
// Logic to update formula and checksum
}
}

Magmi import update option

does Magmi has a option to disable or make quantity to 0 for products not in csv file in import?.
Because my supplier remove all out of stock products from csv file.
If someone can help me on this or finding another solution please.
Thank you in advance
I've created a plugin that disables files not in the CSV. I prefer disabling the items, instead of actually deleting them in case something goes wrong (it won't wipe my database).
Create the plugin file magmi/plugins/extra/general/itemdisabler/magmi_itemdisabler_plugin.php
In the file, paste in the following and save:
Plugin Code:
<?php
class Magmi_ItemdisablerPlugin extends Magmi_ItemProcessor
{
protected $datasource_skus = array();
public function getPluginInfo()
{
return array("name"=>"Magmi Magento Item Disabler",
"author"=>"Axel Norvell (axelnorvell.com)",
"version"=>"1.0.6");
}
public function afterImport()
{
$this->log("Running Item Disabler Plugin","info");
$this->disableItems();
return true;
}
public function getPluginParams($params)
{
return array();
}
public function isRunnable()
{
return array(true,"");
}
public function initialize($params)
{
}
public function processItemAfterId(&$item,$params=null)
{
if(isset($item['sku']))
{
$this->datasource_skus[] = $item['sku'];
}
}
public function disableItems()
{
if(count($this->datasource_skus) <= 0)
{
$this->log('No items were found in datasource. Item Disabler will not run.', "info");
return false; /* Nothing to disable */
}
//Setup tables
$ea = $prefix!=""?$prefix."eav_attribute":"eav_attribute";
$eet = $prefix!=""?$prefix."eav_entity_type":"eav_entity_type";
$cpe = $prefix!=""?$prefix."catalog_product_entity":"catalog_product_entity";
$cpei = $prefix!=""?$prefix."catalog_product_entity_int":"catalog_product_entity_int";
//Get "status" attribute_id
$status_attr_id = "
SELECT ea.attribute_id FROM $ea ea
LEFT JOIN $eet eet ON ea.entity_type_id = eet.entity_type_id
WHERE ea.attribute_code = 'status'
AND eet.entity_type_code = 'catalog_product'";
$result = $this->selectAll($status_attr_id);
if (count($result) == 1) {
$attribute_id = $result[0]['attribute_id'];
}
unset($result);
//Get all active items
$sql = "SELECT e.sku, e.entity_id FROM $cpei i
INNER JOIN $cpe e ON
e.entity_id = i.entity_id
WHERE attribute_id=?
AND i.value = 1";
$all_magento_items = $this->selectAll($sql, array($attribute_id));
//Setup the magento_skus array for easy processing.
$magento_skus = array();
foreach($all_magento_items as $item)
{
$this->log("{$item['sku']} found in Mage", "info");
$magento_skus[$item['sku']] = $item['entity_id'];
}
//process the array, move anything thats in the datasource.
foreach($this->datasource_skus as $sku)
{
if(isset($magento_skus[$sku]))
{
unset($magento_skus[$sku]);
}
}
if(!empty($magento_skus))
{
foreach($magento_skus as $sku => $id)
{
$this->log("Disabling Item Id $id with SKU: $sku", "info");
$this->update("
UPDATE $cpei i
INNER JOIN $cpe e ON
e.entity_id = i.entity_id
SET VALUE = '2'
WHERE attribute_id = ?
AND i.value = 1
AND e.sku=?", array($attribute_id, $sku));
}
}
else
{
//If the Datasource contains all Magento's items.
$this->log('All items present in datasource. No items to disable.', "info");
}
}
}
Then login to Magmi, enable the plugin and run the import. This plugin will execute after the import has completed. It opens the datasource, logs all of the SKUs, then compares them against the Magento database. Any skus that aren't found in the datasource are disabled. This plugin could be optimized a bit better but it works as it is right now.

Pass fees from one shipping method to another

I have a tricky shipping issue that I'm trying to work out. I have a custom extension that calculates the table rates for all of the domestic shipping. But for international, one type of product(category A) is a flat $35/product shipping fee and the rest of the products (categories B and C) are calculated by UPS and USPS. The only way I've been able to figure out how to properly calculate shipping if a customer purchases both types of products is to create a table rate for Category A, then pass it along to UPS/USPS as a handling fee. Is there a variable/method I can use for this process? I haven't yet found one.
As requested, here's my function:
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
// Cut out code where it adds up the categories and the number of items in each category
$rates = $this->getRates($request, $_categories);
if (!empty($rates))
{
$rateTypes = array();
foreach($rates as $rate)
{
$rateTypes[] = $rate['method_name'];
}
$rateTypes = array_unique($rateTypes);
$i=0;
// Create array to pass along to UPS/USPS, if needed
$tempCategories = $_categories;
foreach($rateTypes as $rateType)
{
$groupPrice = 0;
foreach($_categories as $category=>$catQty)
{
$rateExists = false;
$standardRate = 0;
foreach($rates as $rate)
{
$rateCats = explode(',',$rate['category_list']);
if(in_array($category,$rateCats) && $rate['method_name'] == $rateType )
{
$rateExists = true;
if($rate['condition_type'] == 'I'){
$ratePrice = $rate['price'] * $catQty;
}
else if ($rate['condition_type'] == 'O') {
$ratePrice = $rate['price'];
}
unset($tempCategories[$category]);
}
else if(in_array($category,$rateCats) && $rate['method_name'] == "Standard" && $rateType != "Standard")
{
if($rate['condition_type'] == 'I'){
$standardRate += $rate['price'] * $catQty;
}
else if ($rate['condition_type'] == 'O') {
$standardRate += $rate['price'];
}
unset($tempCategories[$category]);
}
}
if($rateExists == false)
{
$groupPrice += $standardRate;
}
else
$groupPrice += $ratePrice;
}
if(count($tempCategories) > 0)
{
// Figure out how to pass the $groupPrice to other shipping methods here
}
else {
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier('shippingcodes');
$method->setCarrierTitle($this->getConfigData('title'));
$method->setMethod('shippingcodes_'.$rateType);
$method->setMethodTitle($rateType);
$method->setPrice($groupPrice);
$result->append($method);
}
}
}
else
return false;
return $result;
}

LINQ query and lambda expressions

I'm trying to write a LINQ query and am having problems. I'm not sure if lambda expressions are the answer or not but I think they may be.
I have two combo boxes on my form: "State" and "Color".
I want to select Widgets from my database based on the values of these two dropdowns.
My widgets can be in one of the following states: Not Started, In Production, In Finishing, In Inventory, Sold. Widgets can have any color in the 'color' table in the database.
The 'state' combobox has selections "Not Sold," "In Production/Finishing", "Not Started," "In Production," "In Finishing," "In Inventory," "Sold." (I hope these are self-explanatory.)
The 'color' dropdown has "All Colors," and a separate item for each color in the database.
How can I create a LINQ query to select the widgets I want from the database based on the dropdowns?
var WidgetStateChoosen = "Sold";
//var WidgetStateChoosen = "All Widgets";
var WidgetColourChoosen = "Orange";
//var WidgetColourChoosen = "All Colours";
var widgetselected = Widgets.Where
(w =>
( (WidgetStateChoosen == "All Widgets") ? (w.WidgetState != WidgetStateChoosen) : (w.WidgetState == WidgetStateChoosen) )
&&
( (WidgetColourChoosen == "All Colours") ? (w.WidgetColour != WidgetColourChoosen) : (w.WidgetColour == WidgetColourChoosen) )
);
Way more code then I wish, but oh well! I wasnt sure I completely understood your state and selectionstate, but I hope my example is still helpful.
[TestMethod]
public void SelectionTest()
{
var userSelections = GetUserSelections("AllColor", (SelectedState[])Enum.GetValues(typeof(SelectedState)));
var inventory = this.GetInventory();
foreach (var currentSelection in userSelections)
{
var selection = currentSelection;
var result = from item in inventory
where (item.Color == selection.Color || selection.Color == "AllColor") &&
this.GetStates(selection.State).Contains(item.State)
select item;
Console.WriteLine("Item selected for selection: Color:{0} SelectedState:{1}", selection.Color, selection.State);
foreach (var item in result)
{
Console.WriteLine("Item Color:{0};Item State:{1}", item.Color, item.State);
}
Console.WriteLine("");
}
}
private IEnumerable<State> GetStates(SelectedState state)
{
var list = new List<State>();
foreach (State currentState in Enum.GetValues(typeof(State)))
{
if (((int)currentState & (int)state) == (int)currentState)
{
list.Add(currentState);
}
}
return list;
}
private IEnumerable<Item> GetInventory()
{
return new List<Item>()
{
new Item() {State = State.NotStarted, Color = "Blue"},
new Item() {State = State.InFinishing, Color = "Red"},
new Item() {State = State.Sold, Color = "Yellow"},
new Item() {State = State.Sold, Color = "Blue"},
new Item() {State = State.InProduction, Color = "Blue"},
new Item() {State = State.InInventory, Color = "Blue"},
};
}
private IEnumerable<UserSelection> GetUserSelections(String color, IEnumerable<SelectedState> states)
{
var list = new List<UserSelection>();
foreach (var state in states)
{
list.Add(new UserSelection() { Color = color, State = state });
}
return list;
}
[Flags]
private enum State
{
NotStarted = 1,
InProduction = 2,
InFinishing = 4,
InInventory = 8,
Sold = 16
}
private enum SelectedState
{
NotSold = State.InInventory, //Where does it map? I assume INInventory even if it doesnt make much sense
InProductionOrFinishing = State.InProduction | State.InFinishing,
NotStarted = State.NotStarted,
InProduction = State.InProduction,
InFinishing = State.InFinishing,
InInventory = State.InInventory,
Sold = State.Sold,
SomeBizarroTrippleState = State.InProduction | State.Sold | State.NotStarted
}
private class UserSelection
{
public String Color { get; set; }
public SelectedState State { get; set; }
}
private class Item
{
public String Color { get; set; }
public State State { get; set; }
}
var query = db.Widgets;
if (stateFilter == "Not sold")
query = query.Where(w => w.State != WidgetState.Sold);
else if (stateFilter == "In Production/Finishing")
query = query.Where(w => w.State == WidgetState.InProduction || w.State == WidgetState.Finishing);
if (colorFilter != "All colors")
query = query.Where(w => w.Color = colorFilter);
(of course you should have a better way of testing the selected value from the combobox, testing on strings is really bad...)

Resources