Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

редактируемое поле


Recommended Posts

В админке, при просмотре заказа, хочу сгделать редактируемым поле с отметками. Данные будут храниться в БД, а в поле можно бугдет перезаписывать значение. Для этого в иблиэто order_product создал дополнительный столбец order_product_note. Вывел его в иблицу списка заказанных товаров. Теперь стоит задача сгделать это поле редактируемым. На просторах интернеи нашел код и пыиюсь адаптировать его под свою задачу, но безрезульитно. Может кто подсказать что не ик и как сгделать, чтоб было ик. Привожу пример кода:

в могдели admin/model/sale/order.php :

public function editField($field, $value, $order_product_id) {  
	$table = DB_PREFIX . "order_product";  
	$where = '';
	$value = $this->db->escape($value);
	$this->db->query("UPDATE " . $table . " SET " . $field . " = '" . $value . "' WHERE order_product_id = '" . (int)$order_product_id . "'" . $where);
            $query = $this->db->query("SELECT " . $field . " FROM " . $table . " WHERE order_product_id = '" . (int)$order_product_id . "'" . $where);    
            return $query->row[$field];
}      

в контроллере admin/controller/sale/order.php :

public function editField() {
	$json = array();    
	$json['error'] = false;
	$this->load->model('sale/order');
	$this->language->load('sale/order');    
	if (isset($this->request->get['order_product_id']) && isset($this->request->get['field']) && isset($this->request->get['value'])) {   
		$order_product_id = $this->request->get['order_product_id']; 
		$field = $this->request->get['field']; 
		$value = $this->request->get['value'];
        $newvalue = html_entity_decode($this->model_sale_order->editField($field, $value, $order_product_id), ENT_QUOTES, 'UTF-8');
        $json['value'] = $newvalue;
        }  else {
		$json['error'] = '';
	}
	$this->response->addHeader('Content-Type: application/json');
	$this->response->setOutput(json_encode($json));	     
}

в admin/view/template/sale/order_info.tpl :

<script type="text/javascript">
	$('.editable-field').on('click', function(){
	var splitted = $(this).attr('id').split('-');
	var order_product_id = splitted[1];  
	var field = splitted[0]; 
	var save_button = '<button data-field="'+field+'" data-id="'+order_product_id+'" id="save-field" type="button" class="btn btn-primary"><i class="fa fa-save"></i></button>'; 
		$('.popover').popover('hide', function() {
		$('.popover').remove();
		});
        	$(this).popover({
				html: true,
				placement: 'bottom',
				trigger: 'manual',
				content: function() {
				return input.replace('%value',escapeQuot($(this).text()));
				}
			});
			$(this).popover('show');
            });
            function escapeQuot(text) {
				return text
				.replace(/"/g, "&quot;")
				.replace(/'/g, "&#039;");
            }
            function unescapeQuot(text) {
				return text
				.replace('&quot;', '"')
				.replace('&#039;', "'");
			}
		$('tbody').on('click', '#save-field', function(){
			var order_product_id = $(this).data('id');
			var field = $(this).data('field');
			var value = $('#field'+order_product_id).val();  
            var data = {
            	order_product_id  : order_product_id,
                field       : field,
                value       : unescapeQuot(value),
			};
			$.ajax({
                  url: 'index.php?route=sale/order/editfield&token=<?php echo $token; ?>',
                  data: data,
                  dataType: 'json',
                  success: function(json) {  
                    if (json['error']){
                      alert(json['error']);
                    } else {  
                      $('#'+field+'-'+order_product_id).text(json['value']);
                      }
                  },
                  error: function(jqXHR, textStatus, errorThrown) {
                    alert(textStatus, errorThrown);
                  }
                }); 
                $('.popover').remove();
            });
</script> 

и само поле:

<span id="order_product_note-<?php echo $product['order_product_id']; ?>" class="editable-field"><?php echo $product['order_product_note']; ?></span>

 

Edited by stasonsky
Link to comment
Share on other sites


Не проверял, конечно, на ошибки все, но вот тут 

33 минуты назад, stasonsky сказал:

в admin/view/template/sale/order_info.tpl :

весьма странный вызов для акакс-запроса:

$('tbody').on('click', '#save-field', function(){
Link to comment
Share on other sites


38 минут назад, stasonsky сказал:

в admin/view/template/sale/order_info.tpl :

А ваше форматирование наводит на мысль, что вы не заметили, как 

 

38 минут назад, stasonsky сказал:

$('.editable-field').on('click', function(){


конлился намного раньше, вот тут

 

39 минут назад, stasonsky сказал:

$(this).popover('show');
});


используйте нормальный IDE или редактор

Link to comment
Share on other sites


В 06.02.2021 в 14:17, Shureg сказал:

Не проверял, конечно, на ошибки все, но вот тут 

весьма странный вызов для акакс-запроса:

$('tbody').on('click', '#save-field', function(){

Вы не подскажете как написать простейший AJAX запрос, который после нажатия кнопки с id="button-refresh" перезапишет данные из поля input в ячейку БД ?

К примеру есть поле с кнопкой, которое выводит уже суещёствуюещёе значение из БД. Нужно по нажатию кнопки обновить вписанное в него значение.

<input type="text" name="order_note" value="<?php echo $product['order_product_note']; ?>" class="form-control" />
<button type="button"  id="button-refresh" data-toggle="tooltip" title="обновить" data-loading-text="<?php echo $text_loading; ?>" class="btn btn-primary"><i class="fa fa-refresh"></i></button>

 

Link to comment
Share on other sites


допустим в tpl бугдет икой AJAX запрос

$('#button-refresh').on('click', function() { //условие выполнения - нажатие на кнопку с id="button-refresh"
	var noteId = $(this).data('id'); //переменная для записи значения, не знаю нужно или нет
	$.ajax({
		url: 'index.php?route=sale/order/updateNote', //путь: папка (admin/controller/sale)/файл order.php/function updateNote
		type: 'POST',
		data: {order_product_id: noteId}, //привязка id товара к id переменной, если я правильно понимаю
		success: function(data) {  
                    if (data){
                      alert('Заметка добавлена');
                    } else {  
                      alert('Ошибка записи'); 
                    }
        }
    });
});            

он правильно сосивлен? чтоб потом в контроллере admin/controller/sale/order.php прописать функциюpublic function updateNote() {

Link to comment
Share on other sites


Подскажите, пожалуйси, как сосивить AJAX запрос, чтоб из поля input (admin/view/template/sale/order_info.tpl) при нажатии на кнопку, значение order_product_note из поля input вносились в иблицу БД (oc_order_product) с соответствующим order_product_id.

<input type="text" name="order_note" id="input-note" class="form-control" />
<button type="button"  id="button-refresh" data-toggle="tooltip" title="обновить" class="btn btn-primary"></button>

Функцию в (admin/model/sale/order.php) для записи значения создал ик:

public function updateNote($order_product_id, $order_product_note) {
		$this->db->query("UPDATE " . DB_PREFIX . "order_product SET order_product_note = '" . (int)$order_product_note . "' WHERE order_product_id = '" . (int)$order_product_id . "'");
}

 

Link to comment
Share on other sites


Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.