How insert array values with foreach in opencart? - foreach

My case similar with this Insert array values with foreach using codeigniter (user input by dynamically adding and removing fields).
But it's CI, I trying in open cart, so I build function insert and passing value(in array) and performs for each in model.
What I want insert is product this for code Controller :
// check request and store to array
if(isset($this->request->get['product']))
{
$product = $this->request->get['product'];
$product2 = array();
foreach($product as $p)
{
$product2[] = $p;
}
}
else
{
$product = null;
}
// This for function insert
public function insert()
{
$this->language->load('item/item');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('item/item');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm())
{
$this->model_item_item->insert_detail($this->request->post);
$this->session->data['success'] = $this->language->get('text_success');
$this->redirect($this->url->link('item/item', 'token=' . $this->session->data['token'], 'SSL'));
}
}
This is for Model :
public function insert_detail($product2)
{
foreach($product2 as $detail)
{
$this->db->query("INSERT INTO " . DB_PREFIX . "show_product_detail SET product_id = '". $this->db->escape($detail['product']) . "'");
}
}
This for View :
<?php echo $header; ?>
<div id="content">
<div class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<?php echo $breadcrumb['separator']; ?><?php echo $breadcrumb['text']; ?>
<?php } ?>
</div>
<?php if ($error_warning) { ?>
<div class="warning"><?php echo $error_warning; ?></div>
<?php } ?>
<?php if ($success) { ?>
<div class="success"><?php echo $success; ?></div>
<?php } ?>
<div class="box">
<div class="heading">
<h1><img src="view/image/product.png" alt="" /> <?php echo $heading_title; ?></h1>
<div class="buttons"><a onclick="$('#form').submit();" class="button"><?php echo $button_save; ?></a><?php echo $button_cancel; ?></div>
</div>
<div class="content">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form">
<table class="form">
<tr>
<td><span class="required">*</span> <?php echo $entry_head; ?></td>
<td><input type="text" name="head_text_field" value="" placeholder="Input Head Text" size="40"/>
<?php if ($error_head) { ?>
<span class="error"><?php echo $error_head; ?></span>
<?php } ?>
</td>
</tr>
<tr>
<td><span class="required">*</span> <?php echo $entry_title; ?></td>
<td><textarea name="title_text_field" placeholder="Input Title Text" style="width:230px;"/></textarea>
<?php if ($error_title) { ?>
<span class="error"><?php echo $error_title; ?></span>
<?php } ?>
</td>
</tr>
<tr>
<td><?php echo $entry_max_item; ?></td>
<td>
<select name="max" id="maxitem">
<?php
for($i=1; $i<=6; $i++)
{
if($i == 1)
echo "<option selected='selected' value=".$i.">".$i."</option>";
else
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td><?php echo $entry_product; ?></td>
<td><input type="text" id="product" name="product" value="" placeholder="Input Product" size="40"/></td>
</tr>
<tr>
<td></td>
<td>
<table>
<tr>
<td><input type="button" id="ADD" value="Add Item"></td>
<td><input type="reset" id="RESET" value="Reset"></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr>
</table>
<table border="1" id="tblname" cellpadding="5" cellspacing="5">
<thead>
<tr>
<td>
Total Item
</td>
<td>
Name Item
</td>
<td>
DELETE
</td>
<tr>
</thead>
<tbody align="center">
</tbody>
</table>
</form>
</div>
</div>
</div>
This for Javascript:
<script type="text/javascript"><!--
$('input[name=\'product\']').autocomplete({
delay: 100,
source: function(request, response) {
$.ajax({
url: 'index.php?route=catalog/product/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(request.term),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
label: item.name,
value: item.product_id
}
}));
}
});
},
select: function(event, ui) {
$('input[name=\'product\']').val(ui.item.label);
return false;
},
focus: function(event, ui) {
return false;
}
});
//--></script>
<Script type="text/javascript">
$(document).ready(function(){
var item = 1;
var isAllowed = 3;
var isSet = 0;
$('#ADD').click(function(){
var maxitem = parseInt($("#maxitem").val(), 10); //from max item in html
var iCount = 0;
if($('#product').val()){ // check input product
if( item <= maxitem )
{
iCount = $('#tblname tbody tr').length + 1;
szTr = "<tr><td>";
szTr = szTr + iCount + "</td>";
szTr = szTr + "<td>" +$('#product').val() +"</td>";
szTr = szTr + "<td><input type='button' class='DEL' value='DELETE'></td>";
szTr = szTr + "</tr>";
$('#tblname tbody').append(szTr);
item +=1;
isSet = 1;
restFormOpts();
}
else
{
alert ("Max Limit !!!");
}
}else{alert('Enter Product !!! ');}
});
// for delete row
$('body').on('click','#RESET', function() {
item = 1;
isAllowed = 3;
isSet = 0;
$("#maxitem").attr("disabled",false);
$('.DEL').parents('tr').remove();
});
$('body').on('click', 'input.DEL', function() {
$(this).parents('tr').remove();
item -= 1;
});
function restFormOpts()
{
if(isSet === isAllowed) {
$("#ADD").attr("disabled",true);
$("#maxitem").attr("disabled",false);
}
else {
$("#ADD").attr("disabled",false);
$("#maxitem").attr("disabled",true);
}
}
});
</script>
This code works to enter into the database , but no contents?
Where i did mistake?

Here's the correct insert statement:
$this->db->query("
INSERT INTO " . DB_PREFIX . "show_product_detail
(show_product_detail)
values ('". $this->db->escape($detail['product']) . "'");

You are putting an array in product_id field.
First you need to change product_id field type int to text and
Check with following code
public function insert_detail($product2)
{
foreach($product2 as $detail)
{
$this->db->query("INSERT INTO " . DB_PREFIX . "show_product_detail SET product_id = '". $this->db->escape(json_encode($detail)) . "'");
}
}

Related

jquery goes on the first page instead mine

I have 2 pages (data-role="page") in my HTML page, in the list page if you go to one detail, save, and try to go into another detail again, it goes to list instead of the detail page.
I tried to follow the code using chrome but the javascript is correct
To change page i use: $.mobile.changePage("#PageAddCustomer");
but it seems working for just 1/2 second, then it goes to the list (who is the first page in the code)
Chrome does not return any javascript error,
just here in stackoverflow preview it returns :"error loading page", with no clues on it
what is wrong ?
I am thinking to use 2 different HTML files, probably it could be an idea
var lat = 0;
var lng = 0;
var map;
var url = "https:////www.suale.it"; //"http://localhost:65386/";//
var urlSito = url+"//GestionePersonale";// "http://localhost:65386/";//
var urlCartellaIMG =url + "//IMGAnnunci";// url+"//public//IMGAnnunci";//
//tiene in memoria
var Categorie;
var Tipologie;
var TipoAnnunci;
var Razze;
$(document).ready(function () {
$("div[data-role='panel']").panel().enhanceWithin();
VaiCustomers();
});
//target the entire page, and listen for touch events
$('html, body').on('touchstart touchmove', function(e){
//prevent native touch activity like scrolling
e.preventDefault();
});
function caricaCustomer(j) {
var $select = $('#cbbInsAdsCustomer');
$select.find('option').remove();
$select.append("<option ></option>");
$.each(j, function (key, value) {
$select.append('<option value=' + value.CodTipologia + '>' + value.DescTipologia + '</option>');
});
}
function GoPage(page) {
//$.mobile.changePage(page);
$(':mobile-pagecontainer').pagecontainer('change', page, {
transition: 'flip',
changeHash: false,
reverse: true,
showLoadMsg: true
});
}
function DoNothing() { }
function CaricaDettagliClienteDetail(J) {
// J = JSON.stringify(J);
J = JSON.parse(J);
$("#txtDetailCliCognome").text(J.Cognome);
$("#txtDetailCliNominativo").text(J.Nominativo);
$("#txtDetailCliIndirizzo").text(J.Indirizzo);
$("#txtDetailCliEmail").text(J.Email);
$("#txtDetailCliCitta").text(J.Citta);
$("#txtDetailCliCellulare").text(J.Cellulare);
$("#txtDetailCliTelefono").text(J.Telefono);
}
function CaricaDatiDetailIMG(data) {
var codAnn = $("#hidCodRapportino").val();
var ico;
var img;
$("#divDetailIMG").empty('');
//img = img.replace('\\', '//').replace('ICO', '');
var x, txt = "";//aggiungo IMG
for (x in data) {
var ico = urlCartellaIMG + "//" + codAnn + "//" + data[x];
var img = ico.replace('ICO', '');
txt += "<img onclick='OpenPopIMG(`" + img + "`)' src='" + ico + "'>";
}
$("#divDetailIMG").html(txt);
}
function GoHEad() {
$.mobile.changePage("#page1");
}
function getToNextPage() {
$.mobile.changePage("#page2");
}
function ScaricaDatiUser() {
var codAnag = $("#hidCodAnagrafica").val();
if (codAnag == '')
{
Messaggio('you must login to see your ads');
return;
}
s = document.createElement("script");
//var Category = $('#cbbSearchCategory option:selected').val();
s.src = urlSito + "/scriptWS.aspx?func=CaricaDatiListaUser&OnErr=Messaggio&modo=ListaUser&codAnag=" + codAnag
//alert(s.src);
document.body.appendChild(s);
}
//#region Customer
function VaiCustomers()
{
if (ControlloLoggato()==false){return;};
GoPage('#PageListCustomer');
CaricaCustomers();
}
function CaricaCustomers()
{
s = document.createElement("script");
var RCodDitta = $('#hidCodDitta').val();
s.src = urlSito + "/scriptWS.aspx?func=CustomersList&OnErr=Messaggio&modo=GetCustomers&CodDitta=" + RCodDitta;
//alert(s.src);
document.body.appendChild(s);
}
function CustomersList(data) {
$('#DTCustomersList').DataTable({
destroy: true,
data: data,
"columns": [
{ "data": "Cognome" },
{ "data": "Nominativo" },
{
"data": "CodAnagrafica",
"mData": function showIMGLista(data, type, dataToSet) {
var J = JSON.stringify(data);
var CodAnagrafica = data.CodAnagrafica;
return "<img src='IMG\\Detail.jpg' onclick='OpenDetailCustomer(" + CodAnagrafica + ");'>";
}
},
]
});
}
function OpenDetailCustomer(CodAnagrafica)//dal principale annuncio carico tutto
{
s = document.createElement("script");
s.src = urlSito + "/scriptWS.aspx?func=CaricaCurstomerDetail&OnErr=Messaggio&modo=GetDetailAnag&CodAnagrafica=" + CodAnagrafica;
document.body.appendChild(s);
//$.mobile.changePage("#PageAddCustomer");
$(':mobile-pagecontainer').pagecontainer('change', '#PageAddCustomer', {
transition: 'flip',
changeHash: false,
reverse: true,
showLoadMsg: true
});
}
function CaricaCurstomerDetail(J) {
// J = JSON.stringify(J);
//J = JSON.parse(J);
$("#txtInsCliCognome").val(J.Cognome);
$("#txtInsCliNominativo").val(J.Nominativo);
$("#txtInsCliIndirizzo").val(J.Indirizzo);
$("#txtInsCliEmail").val(J.Email);
$("#txtInsCliCitta").val(J.Citta);
$("#txtInsCliTelefono").val(J.Cellulare);
$("#txtInsCliCellulare").val(J.Telefono);
$("#hidCodCustomer").val(J.CodAnagrafica);
}
function ConfirmDeleteCustomer()
{
bootbox.confirm("Are you sure?", function (result)
{
if (result) {
DeleteCustomer();
}
});
}
function DeleteCustomer()
{
var CodAnagrafica= $("#hidCodCustomer").val();
s = document.createElement("script");
s.src = urlSito + "/scriptWS.aspx?func=CaricaCustomers&OnErr=Messaggio&modo=DeleteCustomer&CodAnagrafica=" + CodAnagrafica;
document.body.appendChild(s);
$.mobile.changePage("#PageListCustomer");
}
function SaveCustomer()
{
if (ControlloSaveCustomer() == true)
{
var Cognome= $("#txtInsCliCognome").val();
var Nominativo= $("#txtInsCliNominativo").val();
var Indirizzo= $("#txtInsCliIndirizzo").val();
var Email= $("#txtInsCliEmail").val();
var Citta= $("#txtInsCliCitta").val();
var Cellulare= $("#txtInsCliTelefono").val();
var Telefono= $("#txtInsCliCellulare").val();
var CodAnagrafica= $("#hidCodCustomer").val();
var RCodDitta = $('#hidCodDitta').val();
s = document.createElement("script");
s.src = urlSito + "/scriptWS.aspx?func=DoNothing&OnErr=Messaggio&modo=SaveAnagrafica&CodAnagrafica=" + CodAnagrafica + "&Cognome=" + Cognome + "&Nominativo=" + Nominativo
+ "&Indirizzo=" + Indirizzo + "&Email=" + Email + "&Citta=" + Citta + "&Cellulare=" + Cellulare + "&Telefono=" + Telefono + "&RCodDitta=" + RCodDitta+ "&Cliente=1";
document.body.appendChild(s);
VaiCustomers();
GoPage('#PageListCustomer');
}
// $.mobile.changePage("#PageListCustomer");
}
function ControlloSaveCustomer() {
$("#txtInsCliCognome").removeClass('inputObbligatorio');
$("#txtInsCliCellulare").removeClass('inputObbligatorio')
$("#txtInsCliNominativo").removeClass('inputObbligatorio')
if ($("#txtInsCliCognome").val() == '') { $("#txtInsCliCognome").addClass('inputObbligatorio'); return false; }
if ($("#txtInsCliCellulare").val() == '') { $("#txtInsCliCellulare").addClass('inputObbligatorio'); return false; }
if ($("#txtInsCliNominativo").val() == '') { $("#txtInsCliNominativo").addClass('inputObbligatorio'); return false; }
return true;
}
//#endregion
function CaricaDatiListaUser(data) {
caricaUserDatatable(data);
}
function ControlloLoggato() {
var codAnag = $("#hidCodAnagrafica").val();
if (codAnag == '') {
Messaggio('you must login to manage ads');
return false;
}
}
.img-container { position: relative; }
.img-container .top {
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.lblDesc {
font-weight: bold !important;
}
.inputObbligatorio {
border: 2px solid #ff0000 !important;
}
.auto-style1 {
height: 25px;
}
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" />
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<input type="hidden" id="hidCodAnagrafica" value="1"/>
<input type="hidden" id="hidCodDitta" value="1"/>
<div data-role="panel" id="menuPanel" data-mini="true" data-rel="popup" style=" z-index: 1;" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-icon-bars ui-btn-icon-left ui-btn-b" data-transition="pop">
<h4>Menu</h4>
<ul data-role="listview">
<!-- <li>List Admin</li>
<li>Your Reports</li>-->
<!-- <li>New Report</li>-->
<li>Customers</li>
<!-- <li>Jobs</li>
<li>Employees</li>-->
<!-- <li>Register</li>
<li>Login</li>
<li><a href="#" onclick='Website2APK.rateUs();'>Rate us</a></li>-->
<!--<img src="img/head2.jpg" />-->
</ul>
</div>
<!--panel-->
<div data-role="page" id="PageListCustomer" style="background-color: #E5E7E9;">
<h2>Customers</h2>
Menu
<table id="DTCustomersList" class="display" style="width: 100%">
<thead>
<tr>
<th>Surname</th>
<th>Name</th>
<th></th>
</tr>
</thead>
</table>
<input class="btn btn-primary" type="submit" onclick="GoPage('#PageAddCustomer');" value="Add" />
</div> <!--- PageListCustomer --->
<div data-role="page" id="PageAddCustomer" style="background-color: #E5E7E9;">
<h2>Customer</h2>
Menu
<input type="hidden" id="hidCodCustomer" />
<form id="frmAddCustomer">
<table style='border-collapse:collapse;' >
<tr>
<td>
<label class="lblDesc">Surname</label>
</td>
<td>
<input type="text" id="txtInsCliCognome" />
</td>
</tr>
<tr>
<td>
<label class="lblDesc">Name</label></td>
<td>
<input type="text" id="txtInsCliNominativo" />
</td>
</tr>
<tr>
<td>
<label class="lblDesc">Address</label></td>
<td>
<input type="text" id="txtInsCliIndirizzo" />
</td>
</tr>
<tr>
<td>
<label class="lblDesc">Email</label></td>
<td>
<input type="text" id="txtInsCliEmail" />
</td>
</tr>
<tr>
<td>
<label class="lblDesc">City</label></td>
<td>
<input type="text" id="txtInsCliCitta" />
</td>
</tr>
<tr>
<td class="auto-style1">
<label class="lblDesc">Mobile Ph.</label></td>
<td class="auto-style1">
<input type="text" id="txtInsCliTelefono" />
</td>
</tr>
<tr>
<td>
<label class="lblDesc">Phone</label></td>
<td>
<input type="text" id="txtInsCliCellulare" />
</td>
</tr>
</table>
<input class="btn btn-primary" type="submit" onclick="SaveCustomer();" value="Save" />
<input class="btn btn-primary" type="submit" onclick=" VaiCustomers();" value="List" />
</form>
</div> <!--- PageAddCustomer --->

MVC Html helper to make a label editable

I have a html table generated in my view, does anyone know of any helpers available that I could use so that one of the fields could be edited in-line.
View:
<table>
<caption>Configuration values for current management group</caption>
<thead>
<tr>
<th scope="col">Device Type</th>
<th scope="col">Section</th>
<th scope="col">Name</th>
<th scope="col">Value</th>
<th scope="col">Operation</th>
</tr>
</thead>
<tbody>
#foreach (var param in Model.ParamData)
{
<tr>
<td>#param.DeviceType</td>
<td>#param.Group</td>
<td>#param.Name</td>
<td>#param.Value</td>
<td>#(param.IsMerge ? "Merge" : "Delete")</td>
</tr>
}
</tbody>
</table>
As you can see there is nothing special here, I would like an edit column that would work in a similar way to a web forms gridview. The only field to be edited would be value, and it would always be a textbox.
Im sure people must have done this before but the only example Ive seen on line was for mvc 1.
I could knock something up using jquery but am sure there must be loads of examples already and dont want to re-invent the wheel.
Ive done it myself, if anyones interested:
#foreach (var param in Model.ParamData)
{
<tr>
<td>#param.DeviceType</td>
<td>#param.Group</td>
<td>#param.Name</td>
<td>
<div class="#("ViewValueDiv_" + param.ParamaterValueId)">
#param.Value
</div>
<div class="#("EditValueDiv_" + param.ParamaterValueId)" style="display:none;">
<input type="text" name="#("EditValue_" + param.ParamaterValueId)" value="#param.Value" class="#("Input_" + param.ParamaterValueId)" />
</div>
</td>
<td>#(param.IsMerge ? "Merge" : "Delete")</td>
<td>
<div class="#("EditButtonDiv_" + param.ParamaterValueId)">
<input type="button" value="Edit" class="EditButton" Id="#param.ParamaterValueId" />
</div>
<div class="#("UpdateCancelButtonDiv_" + param.ParamaterValueId)" style="display:none;">
<input type="button" value="Update" class="UpdateButton" id="#("U" + param.ParamaterValueId)" />
<input type="button" value="Cancel" class="CancelButton" id="#("C" + param.ParamaterValueId)" />
</div>
</td>
</tr>
}
$(document).ready(function () {
$(".EditButton").click(function () {
var id = $(this).attr('id');
$(".ViewValueDiv_" + id).hide();
$(".EditValueDiv_" + id).show();
$(".EditButtonDiv_" + id).hide();
$(".UpdateCancelButtonDiv_" + id).show();
oldvalue = $(".Input_" + id).val();
});
$(".CancelButton").click(function () {
var id = $(this).attr('id').substr($(this).attr('id').indexOf("C") + 1);
$(".ViewValueDiv_" + id).show();
$(".EditValueDiv_" + id).hide();
$(".EditButtonDiv_" + id).show();
$(".UpdateCancelButtonDiv_" + id).hide();
$(".Input_" + id).val(oldvalue);
});
$(".UpdateButton").click(function () {
var id = $(this).attr('id').substr($(this).attr('id').indexOf("U") + 1);
NewValue = $(".Input_" + id).val();
if (NewValue) {
$.ajax({
url: "/Terminals_configuration/UpdateConfigValue",
data: { valueId: id, newValue: NewValue },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
$(".ViewValueDiv_" + id).show();
$(".EditValueDiv_" + id).hide();
$(".EditButtonDiv_" + id).show();
$(".UpdateCancelButtonDiv_" + id).hide();
$(".ViewValueDiv_" + id).html(NewValue);
}
});
} else {
alert("You didn't supply a new value");
}
});
});

entityAspect.setDeleted doesn't fire the subscribed propertyChanged event

I am running into problem where i subscribe to propertyChanged event, the subscribed event does fire for entity Modification, but never fires for when setting entity to Deleted.
what might i be doing wrong.
The objective of what i am doing is that, whenever user modifies the row, i want to provide
button at row level to cancel the changes. similarly when user deletes a row, i want to provide a button to unDelete a row. The modification part works as expected, but for Delete it is not working.
I was Expecting that item.entityAspect.setDeleted(), would fire the propertyChanged Event
so that i can update the vlaue of observable IsDeleted,which in turn would update the visibility of the button.
ViewModel
/// <reference path="jquery-1.8.3.js" />
/// <reference path="../linq-vsdoc.js" />
/// <reference path="../linq.min.js" />
/// <reference path="../breeze.intellisense.js" />
/// <reference path="../breeze.debug.js" />
$(document).ready(function () {
//extend country type
var Country = function () {
console.log("Country initialized");
var self = this;
self.Country_ID = ko.observable(0); // default FirstName
self.Country_Code = ko.observable(""); // default LastName
self.Country_Name = ko.observable("");
self.entityState = ko.observable("");
self.hasValidationErrors = ko.observable(false);
self.IsDeleted = ko.observable(false);
self.IsModified = ko.observable(false);
self.templateName = ko.observable("AlwayEditable");
var onChange = function () {
var hasError = self.entityAspect.getValidationErrors().length > 0;
if (hasError)
self.hasValidationErrors(true);
else
self.hasValidationErrors(false);
};
//dummy property to wireup event
//should not be used for any other purpose
self.hasError = ko.computed(
{
read: function () {
self.entityAspect // ... and when errors collection changes
.validationErrorsChanged.subscribe(onChange);
},
// required because entityAspect property will not be available till Query
// return some data
deferEvaluation: true
});
//dummy property to wireupEvent and updated self.entityStateChanged property
self.entityStateChanged = ko.computed({
read: function () {
self.entityAspect.propertyChanged.subscribe(function (changeArgs) {
if (changeArgs.entity.entityAspect.entityState.name == "Deleted") {
self.IsDeleted(false);
}
else if (changeArgs.entity.entityAspect.entityState.name == "Modified")
self.IsModified(true);
}); //subscribe
},
deferEvaluation: true,
// self.entityStateChanged(false)
});
self.fullName = ko.computed(
function () {
return self.Country_Code() + " --- " + self.Country_Name();
});
};
manager.metadataStore.registerEntityTypeCtor("Country", Country);
var countryViewModel = function (manager) {
var self = this;
window.viewModel = self;
self.list = ko.observableArray([]);
self.pageSize = ko.observable(2);
self.pageIndex = ko.observable(0);
self.selectedItem = ko.observable();
self.hasChanges = ko.observable(false);
self.totalRows = ko.observable(0);
self.totalServerRows = ko.observable(0);
self.RowsModified = ko.observable(false);
self.RowsAdded = ko.observable(false);
self.RowsDeleted = ko.observable(false);
self.templateToUse = function (dataItem, context) {
var item = dataItem;
if (!_itemTemplate) {
_itemTemplate = ko.computed(function (item) {
//var x = this;
if (this.entityAspect == "undefined")
return this.templateName("AlwayEditable");
if (this.entityAspect.entityState.name == "Deleted") {
this.templateName("readOnlyTmpl");
return this.templateName();
}
else {
this.templateName("AlwayEditable");
return this.templateName();
}
}, item);
}
if (item.entityAspect.entityState.name == "Deleted") {
item.templateName("readOnlyTmpl");
return item.templateName();
}
else {
item.templateName("AlwayEditable");
return item.templateName();
}
// return _itemTemplate();
}
var _itemTemplate;
self.hasError = ko.computed(
{
read: function () {
self.entityAspect // ... and when errors collection changes
.validationErrorsChanged.subscribe(onChange);
},
// required because entityAspect property will not be available till Query
// return some data
deferEvaluation: true
});
self.acceptChanges = function (item) {
// self.selectedItem().entityAspect.acceptChanges();
self.selectedItem(null);
}
manager.hasChanges.subscribe(function (newvalue) {
self.hasChanges(newvalue.hasChanges);
});
self.edit = function (item, element) {
highlightRow(element.currentTarget, item);
self.selectedItem(item);
};
self.discardChanges = function () {
manager.rejectChanges();
manager.clear();
self.pageIndex(0);
self.loadData();
};
self.cancel = function (item, element) {
item.entityAspect.rejectChanges();
self.selectedItem(null);
};
self.add = function () {
var countryType = manager.metadataStore.getEntityType("Country"); // [1]
var newCountry = countryType.createEntity(); // [2]
//if not using this line, the table is not updated to show this newly added item
self.list.push(newCountry);
manager.addEntity(newCountry); // [3]
self.selectedItem(newCountry);
};
self.remove = function (item) {
item.entityAspect.rejectChanges();
item.entityAspect.setDeleted(); //was expecting that propertychaged subscribe event will fire, but it does not
item.templateName("readOnlyTmpl"); //if i don't do this the template is not changed/updated
item.IsDeleted(true); //have to use this
};
self.UndoDelete = function (item) {
item.entityAspect.rejectChanges();
item.templateName("AlwayEditable");
item.IsDeleted(false);
};
self.save = function () {
if (manager.hasChanges()) {
alertTimerId = setTimeout(function () {
//this works as well
$.blockUI({ message: '<img src="Images/360.gif" /> </p><h1>Please Saving Changes</h1>', css: { width: '275px' } });
}, 700);
manager.saveChanges()
.then(saveSucceeded(alertTimerId))
.fail(saveFailed);
} else {
$.pnotify({
title: 'Save Changes',
text: "Nothing to save"
});
// alert("Nothing to save");
};
};
manager.hasChanges.subscribe(function (newvalue) {
self.hasChanges(newvalue.hasChanges);
});
manager.entityChanged.subscribe(function (changeArg) {
self.RowsDeleted(manager.getEntities(null, [breeze.EntityState.Deleted]).length);
self.RowsModified(manager.getEntities(null, [breeze.EntityState.Modified]).length);
self.RowsAdded(manager.getEntities(null, [breeze.EntityState.Added]).length);
});
//we want maxPageIndex to be recalculated as soon as totalRows or pageSize changes
self.maxPageIndex = ko.dependentObservable(function () {
return Math.ceil(self.totalRows() / self.pageSize()) - 1;
//return Math.ceil(self.list().length / self.pageSize()) - 1;
});
self.previousPage = function () {
if (self.pageIndex() > 1) {
self.pageIndex(self.pageIndex() - 1);
//self.loadData();
getData();
}
};
self.nextPage = function () {
if (self.pageIndex() < self.maxPageIndex()) {
self.pageIndex(self.pageIndex() + 1);
// self.loadData();
getData();
}
};
self.allPages = ko.dependentObservable(function () {
var pages = [];
for (i = 0; i <= self.maxPageIndex() ; i++) {
pages.push({ pageNumber: (i + 1) });
}
return pages;
});
self.moveToPage = function (index) {
self.pageIndex(index);
//self.loadData();
getData();
};
};
// self.loadData
var vm = new countryViewModel(manager);
//ko.validation.group(vm);
ko.applyBindings(vm);
// ko.applyBindingsWithValidation(vm);
vm.loadData();
try {
} catch (e) {
displayModalMessage("Page Error :- Reload the Page", e.message);
}
}); //end document.ready
View
<p><a class="btn btn-primary" data-bind="click: $root.add" href="#" title="Add New Country"><i class="icon-plus"></i> Add Country</a></p>
<span> Search Country Code :</span><input id="txtSearch" type="text" /><input id="BtnSearch" type="button" value="Search" data-bind="click: $root.loadData" />
<!--<table class="table table-striped table-bordered " style="width: 700px">-->
<!--<table id="myTable" class="ui-widget" style="width: 800px">-->
<table id="myTable" class="table table-striped table-bordered " style="width: 1200px">
<caption> <div>
<span class="label label-info">Number of Rows Added </span> <span class="badge badge-info" data-bind="text: RowsAdded"></span> ,
<span class="label label-success">Number of Rows Modified</span> <span class="badge badge-success" data-bind="text: RowsModified"></span> ,
<span class="label label-important">Number of Rows Deleted</span> <span class="badge badge-important" data-bind="text: RowsDeleted"></span>
<p/>
</div></caption>
<thead class="ui-widget-header">
<tr>
<th>Code</th>
<th>Name</th>
<th>Full Name</th>
<th />
</tr>
</thead>
<!--<tbody data-bind=" title:ko.computed(function() { debugger; }), template:{name:templateToUse, foreach: list, afterRender: HighlightRows }" class="ui-widget-content"></tbody>-->
<tbody data-bind=" title:ko.computed(function() { debugger; }), template:{name:templateToUse, foreach: list}" ></tbody>
</table>
<div class="pagination">
<ul><li data-bind="css: { disabled: pageIndex() === 0 }">Previous</li></ul>
<ul data-bind="foreach: allPages">
<li data-bind="css: { active: $data.pageNumber === ($root.pageIndex() + 1) }"></li>
</ul>
<ul><li data-bind="css: { disabled: pageIndex() === maxPageIndex() }">Next</li></ul>
</div>
<!--<input id="Button1" type="button" value="Save" data-bind="attr: { disabled: !hasChanges()}, click:saveChanges" />-->
<a class="btn btn-success btn-primary" data-bind="click: $root.save, css: { disabled: !$root.hasChanges()}" href="#" title="Save Changes"> Save Changes</a>
<!-- <input id="Button3" type="button" value="Create New" data-bind="click:AddNewCountry" />
<input id="Button4" type="button" value="Discard and reload data" data-bind="click:discardreload, attr: { disabled: !hasChanges()}" /> -->
<a class="btn btn-danger btn-primary" data-bind="click: $root.discardChanges, css: { disabled: !$root.hasChanges()}" href="#" title="Discard Changes"><i class="icon-refresh"></i> Discard & Reload</a>
<script id="readOnlyTmpl" type="text/html">
<tr >
<td>
<span class="label " data-bind="text: Country_Code "></span>
<div data-bind="if: hasValidationErrors">
<span class="label label-important" data-bind="text: $data.entityAspect.getValidationErrors('Country_Code')[0].errorMessage ">Important</span>
</div>
</td>
<td>
<span class="label " data-bind="text: Country_Name "></span>
<p data-bind="validationMessage: Country_Name"></p>
<span data-bind='visible: ko.computed(function() { debugger; }), text: Country_Name.validationMessage'> </span>
</td>
<td> <span class="label " data-bind="text: fullName "></span>
</td>
<td >
<a class="btn btn-danger" data-bind="click: $root.cancel, visible: $data.IsModified" href="#" title="cancel/undo changes">Undo Changes<i class="icon-trash"></i></a>
<a class="btn btn-danger" data-bind="click: $root.remove, visible: !$data.IsDeleted() " href="#" title="Delete this Row">Delete<i class="icon-remove"></i></a>
<a class="btn btn-danger" data-bind="click: $root.UndoDelete, visible: $data.IsDeleted() " href="#" title="Undo Delete">Un Delete<i class="icon-remove"></i></a>
</td>
</tr>
</script>
<script id="AlwayEditable" type="text/html">
<tr >
<td><input type="text" placeholder="Country Code" data-bind="value: Country_Code , uniqueName: true, css: { error: hasValidationErrors }, valueUpdate: 'afterkeydown'"/>
<!-- <div data-bind="if: $data.entityAspect.getValidationErrors().length>0">
<pre data-bind="text: $data.entityAspect.getValidationErrors('Country_Code')[0].errorMessage "></pre>
</div>-->
<div data-bind="if: hasValidationErrors">
<span class="label label-important" data-bind="text: $data.entityAspect.getValidationErrors('Country_Code')[0].errorMessage ">Important</span>
</div>
</td>
<td><input type="text" placeholder="Country Name" data-bind="value: Country_Name, uniqueName: true, valueUpdate: 'afterkeydown'"/>
<p data-bind="validationMessage: Country_Name"></p>
<span data-bind='visible: ko.computed(function() { debugger; }), text: Country_Name.validationMessage'> </span>
</td>
<td>
<span data-bind=' text: fullName'> </span>
</td>
<td >
<a class="btn btn-danger" data-bind="click: $root.cancel, visible: $data.IsModified" href="#" title="cancel/undo changes">Undo Changes<i class="icon-trash"></i></a>
<a class="btn btn-danger" data-bind="click: $root.remove, visible: !$data.IsDeleted() " href="#" title="Delete this Row">Delete<i class="icon-remove"></i></a>
<a class="btn btn-danger" data-bind="click: $root.UndoDelete, visible: $data.IsDeleted() " href="#" title="Undo Delete">Un Delete<i class="icon-remove"></i></a>
</td>
</tr>
</script>
Analysis
The propertyChanged event is raised when ... a property changes. But that's not what you want to watch. You want to monitor the entityAspect.entityState
When you set a property to a new value (for example person.FirstName("Naunihal")), you get both a propertyChanged event and a change to the entity's EntityState.
When you delete the entity, the entity's EntityState changes ... to "Deleted". But deleting doesn't change a property of the entity. Breeze does not consider the EntityState itself to be a property of the entity. Therefore, there is no propertyChanged notification.
Solution
Update Jan 12, 2013
I think more people will discover this solution if I rephrase the question that you asked so people understand that you want to listen for changes to EntityState.
So I moved my answer to a new SO question: "How can I detect a change to an entity's EntityState?". Hope you don't mind following that link.

PHP handling multiple checkboxes

Ok, I have index.html with a form as follows:
<form action="process.php" method="post">
<table>
<tr>
<td><input name="Field[]" type="checkbox" value="Accounting" />Accounting</td>
<td><input name="Field[]" type="checkbox" value="Finance" />Finance</td>
<td><input name="Field[]" type="checkbox" value="Marketing" />Marketing</td>
</tr>
</table>
</form>
And I have process.php as follows:
<table>
<tr>
<th>Field(s):</th>
<td>
<?php
if(isset($_POST['Field']))
{
for($i = 0; $i < count($_POST['Field']); $i++)
{ echo $_POST['Field'][$i] . ' '; }
}
?>
</td>
</tr>
</table>
Yet for some reason, I only get the first letter of the last checkbox that was checked printed out. Help please!
Try this one in process.php to get the values from $_POST['Field']
<table>
<tr>
<th>Field(s):</th>
<td>
<?php
if(isset($_POST['Field']))
{
foreach ($_POST['Field'] as $value) {
echo $value;
}
}
?>
</td>
</tr>
</table>

Pass filename as parameter to Controller through jQuery

I am trying to upload an image using jQuery-ui dialog and pass the image file to the controller which will actually do the uploading work. However, I can't seem to get it right. The code is given below
View:
<table>
<tr>
<th>
Image
</th>
<th>
Name
</th>
</tr>
#foreach (var item in Model.CourseApplicationForms)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.thumbnail)
</td>
<td>
#Html.DisplayFor(modelItem => item.sname)
</td>
<td>
Upload File
</td>
</tr>
}
</table>
<div id="dialog" title="Upload files">
#using(Html.BeginForm("ImageUpload","Student", FormMethod.Post, new {id="photouploadform", enctype = "multipart/form-data" }))
{
<p><input type="file" id="fileUpload" name="fileUpload" size="23"/> </p><br />
<p><input type="submit" value="Upload file" /></p>
<input type="hidden" id="EnrollId" />
}
</div>
<script type="text/javascript">
$(function () {
$('.photoupload').click(function (event) {
$('#EnrollId').val(event.target.id);
$('#dialog').dialog('open');
});
$('#photouploadform').submit(function () {
$.getJSON("/Student/ImageUpload/", {
Id: $('#EnrollId').val(), file: $('#fileUpload')
}, function (data) {
$('#dialog').append('<p>' + data + '</p>');
});
return false;
});
$("#dialog").dialog({
autoOpen: false,
show: "blind",
width: 400,
hide: "fade",
modal: true,
resizable: false
});
});
</script>
Controller
[AcceptVerbs(HttpVerbs.Get)]
JsonResult ImageUpload(int Id, HttpPostedFileBase file = null)
{
string filePath = string.Empty;
if (file.ContentLength > 0)
{
Directory.CreateDirectory(HttpContext.Server.MapPath("~/Content/Photo/medium"));
filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/Photo/medium"), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
return Json(filePath, JsonRequestBehavior.AllowGet);
}
I want to pass the fileupload image but don't have a clue how to do it. Kindly help
Thanks in advance

Resources