getElementById from select box to text field - database

Im making a selectbox with the values from my DB, and I want to write the ID of the selected item to a textbox.
How can it be done? I have this code..
<form method="POST" action="" id="submitKon">
<fieldset>
<table class="opretTable" border="0">
<tr>
<td width="180" height="30"><label for="valgtkon" class="labelLeft">Vælg konkurrencetype</label></td>
<td><select id="valgtTitel" name="valgtTitel" onchange="run()">
<?php
$virksomhedsID = $_SESSION['virkID'];
$sql = "SELECT * FROM konkurrenceType ORDER BY konkurrenceType.kontypeID";
$result = mysql_query($sql) or die(mysql_error());
echo '<option value="Vælg type">Vælg type</option>';
while($rowSelect = mysql_fetch_assoc($result))
{
echo '<option value="' . $rowSelect['kontypeID'] . '">' . $rowSelect['kontypeTitel'] . '</option>';
}?>
</select>
and..
<script>
function run() {
document.getElementById("valgtID").value = document.getElementById("valgtTitel").value;
}
</script>
I get this
INSERT INTO `mah1233411190550`.`konkurrence` ( `konID` , `virkID` , `konTitel` , `konBeskriv` , `konMaal` , `konMaaltype` , `konStart` , `konSlut`, `kontypeID`, `holdID` ) VALUES (NULL , '1', '1', 'cykle', '500', 'km', '2013-01-01', '2018-05-03', '1', '' );
So konTitel is the same as kontypeID, why is that?

You can do something like:
var valgtTitel = document.getElementById("valgtTitel");
document.getElementById("valgtID").value = valgtTitel.options[valgtTitel.selectedIndex].value;
Here's fiddle: http://jsfiddle.net/viralpatel/JYHLM/
Edit:
Perhaps you might want to save the title (apart from ID) in some other textbox and retrieve it from request:
var valgtTitel = document.getElementById("valgtTitel");
document.getElementById("valgtTitle").value = valgtTitel.options[valgtTitel.selectedIndex].innerHTML;
Note how we used innerHTML instead of value to get the title.

So something like this??
<tr>
<td width="180" height="30"><label for="valgtkon" class="labelLeft">Vælg konkurrencetype</label></td>
<td><select id="select" name="select" onchange="run()">
<?php
$virksomhedsID = $_SESSION['virkID'];
$sql = "SELECT * FROM konkurrenceType ORDER BY konkurrenceType.kontypeID";
$result = mysql_query($sql) or die(mysql_error());
echo '<option value="Vælg type">Vælg type</option>';
while($rowSelect = mysql_fetch_assoc($result))
{
$kontypeID = $rowSelect['kontypeID'];
$kontypeTitel = $rowSelect['kontypeTitel'];
echo '<option value="' . $kontypeID . '">' . $kontypeTitel . '</option>';
}?>
</select></td>
<script>
function run() {
var select = document.getElementById("select");
document.getElementById("valgtID").value = valgtTitel.options[select.selectedIndex].innerHTML; //how to make this right?
document.getElementById("valgtTitel").value = valgtTitel.options[select.selectedIndex].innerHTML; //how to make this right?
}
</script>
<td><input type="text" name="valgtID" id="valgtID"/><input type="text" name="valgtTitel" id="valgtTitel"/></td>
</tr>

Related

Laravel: Updating multiple files in array

I was able to store and save multiple files in the array into the database, as well as updating the form data. However, the problem now is it returns this error when I update the form without updating the file.
count(): Parameter must be an array or an object that implements Countable
Does anyone know what should I do for my update function or value in my blade file so that it won't delete the file elements?
--------------------------------------------- UPDATED ---------------------------------------------
public function update(Request $request, $id)
{
$data = $request->all();
$data = $this->saveEmptyData($data);
$c = Document::find($id);
$fileData = [];
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('storage/documents');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc = json_encode($fileData);
$c->file = $doc;
$c->name = $request->name;
$c->price = $request->price;
$c->publish = $request->publish;
}
//else {
// redirect()->back()->with('errors', 'File is required!');
//}
$c->save();
return redirect()->route('product.index')->with('success', 'Document updated successfully');
}
Blade
<form method="POST" action="{{ route('document.update', $doc) }}" enctype="multipart/form-data">
<fieldset>
....
<div class="form-group">
<label>Document</label>
<div class="input-group-append">
<label for="upload_file">Upload</label>
<input id="upload_file" type="file" name="file[]" value="{{ isset($doc) ? $doc['file'] : '' }}" multiple>
</div>
</div>
</fieldset>
</form>
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('documents/');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc= json_encode($fileData); //replace $doc['file'] with $doc
$c->file=$doc;
}
$c->save();
//not required to declare $fileData ;
enctype="multipart/form-data" in form tag
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('documents/');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc['file'] = json_encode($fileData);
}

Laravel insert dynamic inputs into database

I'm trying to save dynamic inputs in multiple rows in my database.
This is a part of my form which are payments and dates.
<tr>
<td class="col-md-2">
{{Form::text('pay[]', '', ['class' => 'form-control number', 'placeholder' => ''])}}
</td>
<td class="col-md-2">
{{Form::text('payDate[]', '', ['class' => 'form-control pDate', 'placeholder' => ''])}}
</td>
<td class="col-md-2"><a class="deleteRow"></a>
</td>
</tr>
My JS code that add inputs dynamically:
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" id="field_2" class="form-control" name="pay[]" /></td>';
cols += '<td><input type="text" class="form-control pDate" name="payDate[]" /></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
And this is my Controller:
$input = $request->all();
for($i=0; $i<= count($input['pay']); $i++) {
$payment = new Payment;
$payment->file = $file;
$prePayment = str_replace(',', '', $request->input('pay'));
$payment->payment = $prePayment;
$payment->paymentDate = $request->input('payDate');
$payment->save();
}
Could you please help me to fix this issue.
At the moment I get this error:
Array to string conversion (SQL: insert into payments (file, payment, paymentDate, updated_at, created_at) values ....
May be $request->input('pay') this line causing the problem as you are trying to fetch whole array here, instead you should fetch single object.
$input = $request->all();
$pays = $request->input('pay');
$paymentDates = $request->input('payDate');
for($i=0; $i< count($input['pay']); $i++) {
$payment = new Payment;
$payment->file = $file;
$prePayment = $pays[$i];
$payment->payment = str_replace(',','',$prePayment);
$payment->paymentDate = $paymentDates[$i];
$payment->save();
}

Quantity is not updating in magento site

we have marketplace multi vendor/seller site. we gave an option for seller to update the product information through frontend.....
As it is marketplace site, we have many sellers.
seller A uploaded product A in frontend [quantity = 20 ]
if seller B have same product , he will assign the same product to his account [quantity = 5 ]
in backend it showing 20 + 5 = 25 quantity.
now the problem is when seller A update the quantity from 20 to 40, it showing 40 in frontend and once we refresh the page, it showing only 35. Means after refreshing it showing quantity of [ Seller A qty- Seller B qty ]
but it should show seller A Quantity.
Before It was working properly , later we did some code changes than we are facing this Problem.
before the qty textfield was looking like as in image :
once we click on "edit " button present in image, it looks like below image :
But we decided to display below image :
so we changed code to look like above image. Than this problem happened.
Before Code : [Everything was working fine ]
<td>
<?php
$selllermpassignproduct=Mage::getModel('mpassignproduct/mpassignproduct')->getAssignProDetails($products->getId());
//Zend_Debug::dump($selllermpassignproduct,null,true);
$stock_item=Mage::getModel('cataloginventory/stock_item')->loadByProduct($products);
$SellerQty=isset($selllermpassignproduct['sellerqty'])?$selllermpassignproduct['sellerqty']:$stock_item->getQty();
$assignqty=isset($selllermpassignproduct['assignqty'])?$selllermpassignproduct['assignqty']:0;
?>
<span id="valueqty_<?php echo $products->getId(); ?>"><?php echo (int) $SellerQty; ?></span>
<input type = "text" id = "qty_<?php echo $products->getId(); ?>" onkeydown="validateNumbers(event)" name = "stock" value = "<?php echo (int) $SellerQty; ?>" style = "display:none"/>
<span class="label wk_action" id="edit_link_<?php echo $products->getId(); ?>">
<img onclick="showField('<?php echo $products->getId(); ?>'); return false;" src="<?php echo $this->getSkinUrl('marketplace/images/icon-edit.png'); ?>"/>
</span>
<p id="updatedqty_<?php echo $products->getId(); ?>" style = "display:none;color:red;">Updated</p>
<br/>
<button id="update_button_<?php echo $products->getId(); ?>" class="buttons" onclick="updateField('<?php echo $products->getId(); ?>',<?php echo $assignqty;?>); return false;" style="display:none" >
<span><span style="font-size:12px;"><?php echo $helper->__('Update') ?></span></span>
</button>
<button id="reset_button_<?php echo $products->getId(); ?>" type="reset" class="cancel" onclick="hideReset('<?php echo $products->getId(); ?>'); return false;" style="display:none" >
<span><span><?php echo $helper->__('Cancel') ?></span></span>
</button>
Script
function hideReset(product_id) {
var qtyId='#qty_'+ product_id;
var editLink="#edit_link_"+ product_id;
var updateButton="#update_button_"+ product_id;
var resetButton="#reset_button_"+ product_id;
$wk_jq(qtyId).hide();
$wk_jq(editLink).show();
$wk_jq(updateButton).hide();
$wk_jq(resetButton).hide();
}
function updateField(product_id,assignqty)
{
var qtyId = '#qty_'+ product_id;
var valueId = '#valueqty_'+ product_id;
var updatedqty = '#updatedqty_'+ product_id;
var editLink = "#edit_link_"+ product_id;
var updateButton = "#update_button_"+ product_id;
var resetButton = "#reset_button"+ product_id;
var url ='<?php echo Mage::getUrl('marketplace/marketplaceaccount/updateField/')?>';
$wk_jq(qtyId).toggle()
$wk_jq(editLink).hide();
$wk_jq(updateButton).show();
$wk_jq(resetButton).show();
$qty = $wk_jq(qtyId).val();
jQuery(valueId).html($qty);
hideReset(product_id);
var tmpQty=assignqty+ parseInt($qty) ;
new Ajax.Request(url, {
method: 'post',
parameters: {id: product_id, qty: tmpQty},
onComplete: function (transport) {
//alert(transport.responseText);
jQuery(priceId).val($price);
// $wk_jq(priceId).setValue($price);
jQuery(updatedqty).show().delay(2000).fadeOut();
$updateButton.prop('disabled', false);
// $wk_jq(qtyId).setValue($qty);
}
});
}
Present code
In the above code, we comment some lines and we replaced some codes as below.
commented code
<!-- <img onclick="showField('<?php echo $products->getId(); ?>'); return false;" src="<?php echo $this->getSkinUrl('marketplace/images/icon-edit.png'); ?> -->
**script**
//$wk_jq(qtyId).toggle()
//$wk_jq(updateButton).show();
//hideReset(product_id);
//jQuery(updatedqty).show().delay(2000).fadeOut();
Replaced code 1 )
<input type = "text" id = "qty_<?php echo $products->getId(); ?>" onkeydown="validateNumbers(event)" name = "stock"
value = "<?php echo (int) $SellerQty; ?>" style = "display:none"/>
to
<input type = "text" id = "qty_<?php echo $products->getId(); ?>" onkeydown="validateNumbers(event)"
name = "stock" class="ama1" value = "<?php echo (int) $SellerQty; ?>" />
Replaced code 2)
var tmpQty=assignqty+ parseInt($qty) ;
new Ajax.Request(url, {
method: 'post',
parameters: {id: product_id, qty: tmpQty},
to
var tmpQty=parseInt(assignqty)+ parseInt($qty) ;
new Ajax.Request(url, {
method: 'post',
parameters: {id: product_id, qty: $qty},
I found solution for 1st problem.
public function massupdatesellerproAction(){
if($this->getRequest()->isPost()){
if(!$this->_validateFormKey()){
$this->_redirect('marketplace/marketplaceaccount/myproductslist/');
}
$ids= $this->getRequest()->getParam('product_mass_update');
$price= $this->getRequest()->getParam('price');
$special= $this->getRequest()->getParam('specialprice');
$i=1;
foreach ($ids as $key => $value) {
$i=$i+1;
$qty = $this->getRequest()->getParam('stock'.$i);
$product = Mage::getModel('catalog/product')->load($value);
$product->setPrice($price[$key]);
$product->setSpecialPrice($special[$key]);
//$product->setQty($qty);
$product->save();
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($value);
$stockItem->setData('manage_stock', 1);
$stockItem->setData('qty', $qty);
$stockItem->save();
}
Mage::getSingleton('core/session')->addSuccess( Mage::helper('marketplace')->__('Products has been sucessfully deleted from your account'));
$this->_redirect('marketplace/marketplaceaccount/myproductslist/');
}}

CodeIgniter Dropdown menu fetching data from database column

I am having a problem. Please let me know if there is a solution. I am new to codeigniter therefore, sorry in advance if there is a silly one!
I am trying to fetch data from a database. Table name is fw_main_cat which have fields (cat_id, cat_parent_id, cat_level, cat_title, cat_menu_order and cat_status). cat_id is unique.
I want a dropdown menu (in view) to take all the data of a column cat_title through cat_level (which are int). So, how can I do?
Here is my code which I have tried so far.
This is Model :
public function cat_level_one($cat_level)
{
$sql = "Select * from fw_main_cat Where cat_level=? ";
$result = $this->db->query($sql, $cat_level);
if($result->num_rows() > 0)
{
return $result->result_array();
}
else { return false;
}
}
This is Controller :
public function getcategory()
{
if ($this->session->userdata('session_status'))
{
$cat_level_one = $this->admin_cat_model->cat_level_one($cat_level);
$data['cat_level_one'] = $this->admin_cat_model->cat_level_one($cat_level);
$this->session->set_userdata('cat_level', $_POST['cat_level']);
$this->laod_view('admin_view/admin_cat/view_add_category', $data);
}else {
redirect ('admin_view/admin_cat/view_category');
}
}
This is View (dropdown menu):
<li class="full-row">
<select name = 'cat_level_one' id = 'cat_level_one'>
<option value="<?php if(isset ($cat_level_one) && $cat_level_one != ''){ foreach ($cat_level_one as $cat_one){ echo $cat_one->cat_id; } } ?>"
selected="selected">------------Select Category------------</option>
Thanks! for the consideration.
Updated code -
// in model
function cat_level_one($cat_level)
{
$this->db->where('cat_level',$cat_level);
$q = $this->db->get('fw_main_cat');
$data = $q->result_array();
return $data;
}
//controller function
public function getcategory()
{
**if ($this->session->userdata('session_status'))
{
$data['cat_level_one'] = $this->admin_cat_model->cat_level_one($cat_level);**
//Where this post data comes from??
$this->session->set_userdata('cat_level', $_POST['cat_level']);
$this->laod_view('admin_view/admin_cat/view_add_category', $data);
}else {
redirect ('admin_view/admin_cat/view_category');
}
}
//in view
<li class="full-row">
<select name = 'cat_level_one' id = 'cat_level_one'>
<option value="">-- Select Category --</option>
<?php foreach($cat_level_one as $cat_one){ ?>
<option value="<?php echo $cat_one->cat_id; ?>"><?php echo $cat_one->cat_title; ?></option>
<?php } ?>
</select>
</li>

CakePHP trouble with posting from select to controller

The value of my select tag doesn't seem tto post to my controller, no matter what I try
The select tag
<select name="whatever">
<?php
foreach($packs as $packName => $pack) {
echo " '<option value=" . $packName . '">' . $packName . '</option>';
}
?>
</select>
Where I try to use it in controller
function procedures() {
$errors = array();
$otsing= "";
if (!isset($this->data)) {
App::import('Helper', 'Formatter');
$formatter = new FormatterHelper();
$this->data['start'] =
$formatter->FormatDate($this->Dating->Now());
$this->data['end'] = $formatter->FormatDate($this->Dating->Now());
if(!empty($_POST['whatever']))
{
$otsing = $this->$_POST['whatever'];
}
}
}
The select name should be wriiten like
data[Formname][selectname]
if you want to give it in HTML format or you should use cakephp way to define dropdwon:
<?php
echo $form->select(‘whatever’,$packs)
?>

Resources