Я пытаюсь вставить в свою таблицу внутренних поставок, но хочу использовать свой собственный первичный ключ (release_note), а не автоматическое увеличение sql. Итак, я сделал поле release_note видимым с помощью
echo $this->Form->input('release_note', ['type' => 'text', 'id' => 'note']);
но каждый раз, когда я пытаюсь добавить новую отправку, текст, который я ввел в этот ввод, никогда не сохраняется и не отправляется в запрос sql, поэтому всегда по умолчанию используется значение NULL.
Это моя таблица внутренних отгрузок
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* InwardShipments Model
*
* @property \App\Model\Table\SuppliersTable|\Cake\ORM\Association\BelongsTo $Suppliers
* @property \App\Model\Table\ShippingMethodsTable|\Cake\ORM\Association\BelongsTo $ShippingMethods
* @property \App\Model\Table\OrdersTable|\Cake\ORM\Association\BelongsTo $Orders
* @property \App\Model\Table\UsersTable|\Cake\ORM\Association\BelongsTo $Users
*
* @method \App\Model\Entity\InwardShipment get($primaryKey, $options = [])
* @method \App\Model\Entity\InwardShipment newEntity($data = null, array $options = [])
* @method \App\Model\Entity\InwardShipment[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\InwardShipment|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\InwardShipment patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\InwardShipment[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\InwardShipment findOrCreate($search, callable $callback = null, $options = [])
*/
class InwardShipmentsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('inward_shipments');
$this->setDisplayField('release_note');
$this->setPrimaryKey('release_note');
$this->belongsTo('Suppliers', [
'foreignKey' => 'supplier_id'
]);
$this->belongsTo('ShippingMethods', [
'foreignKey' => 'shipping_method_id'
]);
$this->belongsTo('Orders', [
'foreignKey' => 'order_id'
]);
$this->belongsTo('Users', [
'foreignKey' => 'user_id'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->allowEmpty('release_note', 'create');
$validator
->date('date')
->allowEmpty('date');
$validator
->numeric('freight_amount')
->allowEmpty('freight_amount');
$validator
->numeric('weight')
->allowEmpty('weight');
$validator
->allowEmpty('supplier_invoice_number');
$validator
->allowEmpty('supplier_release_note');
$validator
->numeric('invoice_total')
->allowEmpty('invoice_total');
$validator
->integer('comercial')
->allowEmpty('comercial');
$validator
->allowEmpty('consignment_no');
$validator
->allowEmpty('notes');
$validator
->integer('dim_l')
->allowEmpty('dim_l');
$validator
->integer('dim_w')
->allowEmpty('dim_w');
$validator
->integer('dim_h')
->allowEmpty('dim_h');
$validator
->numeric('volume')
->allowEmpty('volume');
$validator
->numeric('volumetric')
->allowEmpty('volumetric');
$validator
->allowEmpty('freight_invoice_no');
$validator
->numeric('USD_exch_rate')
->allowEmpty('USD_exch_rate');
$validator
->numeric('freight_costs')
->allowEmpty('freight_costs');
$validator
->numeric('customs_costs')
->allowEmpty('customs_costs');
$validator
->integer('freight_added')
->allowEmpty('freight_added');
$validator
->allowEmpty('certification_type');
$validator
->numeric('bank_charges')
->allowEmpty('bank_charges');
$validator
->numeric('other_charges')
->allowEmpty('other_charges');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['supplier_id'], 'Suppliers'));
$rules->add($rules->existsIn(['shipping_method_id'], 'ShippingMethods'));
$rules->add($rules->existsIn(['order_id'], 'Orders'));
$rules->add($rules->existsIn(['user_id'], 'Users'));
return $rules;
}
}
Это мой метод добавления InwardsShipmentsController.
public function add()
{
$inwardShipment = $this->InwardShipments->newEntity();
if ($this->request->is('post')) {
$inwardShipment = $this->InwardShipments->patchEntity($inwardShipment, $this->request->data);
if ($this->InwardShipments->save($inwardShipment)) {
$this->Flash->success(__('The {0} has been saved.', 'Inward Shipment'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The {0} could not be saved. Please, try again.', 'Inward Shipment'));
}
}
а это мой add.ctp там скрипт для установки release_note внизу
<link rel = "stylesheet" href = "https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<?php use Cake\Routing\Router; ?>
<section class = "content-header">
<h1>
Inward Shipment
<small><?= __('Add') ?></small>
</h1>
<ol class = "breadcrumb">
<li>
<?= $this->Html->link('<i class = "fa fa-dashboard"></i> '.__('Back'), ['action' => 'index'], ['escape' => false]) ?>
</li>
</ol>
</section>
<!-- Main content -->
<section class = "content">
<div class = "row">
<!-- left column -->
<div class = "col-md-12">
<!-- general form elements -->
<div class = "box box-primary">
<div class = "box-header with-border">
<h3 class = "box-title"><?= __('Form') ?></h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<?= $this->Form->create($inwardShipment, array('role' => 'form')) ?>
<div class = "box-body">
<div class = "col-md-6">
<?php
echo $this->Form->input('release_note', ['type' => 'text', 'disabled' => 'disabled', 'id' => 'note']);
echo $this->Form->input('date', ['empty' => true, 'default' => '', 'class' => 'datepicker form-control', 'type' => 'text']);
echo $this->Form->input('supplier_id', ['type' => 'hidden', 'id'=>'id']);
echo $this->Form->input('supplier_name', ['type' => 'text', 'empty' => true, 'id' => 'supplier']);
echo $this->Form->input('shipping_method_id', ['options' => $shippingMethods, 'empty' => true]);
echo $this->Form->input('weight');
echo $this->Form->input('freight_invoice_no');
echo $this->Form->input('supplier_invoice_number');
echo $this->Form->input('supplier_release_note');
echo $this->Form->input('order_id', ['options' => $orders, 'empty' => true]);
echo $this->Form->input('consignment_no');
echo $this->Form->input('notes');
echo $this->Form->input('user_id', ['options' => $users, 'empty' => true]);
echo $this->Form->input('certification_type');
echo $this->Form->input('comercial', ['type' => 'checkbox', 'id'=>'comercial']);
?>
</div>
<div class = "col-md-6">
<?php
echo $this->Form->input('dim_l');
echo $this->Form->input('dim_w');
echo $this->Form->input('dim_h');
echo $this->Form->input('volume');
echo $this->Form->input('volumetric');
echo $this->Form->input('freight_costs');
echo $this->Form->input('bank_charges', ['id' => 'bank']);
echo $this->Form->input('other_charges');
echo $this->Form->input('customs_costs', ['id' => 'customs']);
echo $this->Form->input('freight_amount');
echo $this->Form->input('invoice_total');
echo $this->Form->input('USD_exch_rate', ['id' => 'rate']);
echo $this->Form->input('freight_added', ['type' => 'checkbox']);
?>
</div>
</div>
<!-- /.box-body -->
<div class = "box-footer">
<?= $this->Form->button(__('Save')) ?>
</div>
<?= $this->Form->end() ?>
</div>
</div>
</div>
</section>
<?php
$this->Html->css([
'AdminLTE./plugins/datepicker/datepicker3',
],
['block' => 'css']);
$this->Html->script([
'AdminLTE./plugins/input-mask/jquery.inputmask',
'AdminLTE./plugins/input-mask/jquery.inputmask.date.extensions',
'AdminLTE./plugins/datepicker/bootstrap-datepicker',
'AdminLTE./plugins/datepicker/locales/bootstrap-datepicker.pt-BR',
],
['block' => 'script']);
?>
<?php $this->start('scriptBottom'); ?>
<script>
$(function () {
//Datemask yyyy-mm-dd
$(".datepicker")
.inputmask("yyyy-mm-dd", {"placeholder": "yyyy-mm-dd"})
.datepicker({
language:'en',
format: 'yyyy-mm-dd'
});
});
</script>
<script>
$('#order_id').autocomplete({
delay: 0,
minLength: 2,
source:'<?php echo Router::url(array('controller' => 'Orders', 'action' => 'search')); ?>'
});
</script>
<script>
$('#supplier').autocomplete({
delay: 0,
minLength: 3,
source:'<?php echo Router::url(array('controller' => 'Suppliers', 'action' => 'search')); ?>'
});
</script>
<script>
document.getElementById('supplier').addEventListener('change',function(){
var supplier_name = this.value;
//alert(supplier_name);
var csrfToken = $('[name=_csrfToken]').val();
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Suppliers", "action" => "fill")); ?>',
headers: {
Accept: "application/json"
},
data: {'supplier_name' : supplier_name},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
success: function(data){
//alert(data);
data = JSON.parse(data);
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "OptionChanges", "action" => "getExchangeRate")); ?>',
headers: {
Accept: "application/json"
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
success: function(data){
//alert(data);
data = JSON.parse(data);
document.getElementById('rate').value = data.value;
}
});
if (data != null){
document.getElementById('id').value = data.id;
//alert("id: " + data.id);
if (data.country_id != '' && data.country_id != 157){
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "OptionChanges", "action" => "getCustomsRate")); ?>',
headers: {
Accept: "application/json"
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
success: function(data){
//alert(data);
data = JSON.parse(data);
document.getElementById('customs').value = data.value;
}
});
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "OptionChanges", "action" => "getBankCharges")); ?>',
headers: {
Accept: "application/json"
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
success: function(data){
//alert(data);
data = JSON.parse(data);
document.getElementById('bank').value = data.value;
}
});
}
}
else{
alert("Invalid supplier name please verify name or create a new supplier")
document.getElementById('supplier').value = "";
document.getElementById('id').value = "";
}
}
});
});
</script>
<script>
$('document').ready(function(){
//alert('ready');
var csrfToken = $('[name=_csrfToken]').val();
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "InwardShipments", "action" => "getLatest")); ?>',
headers: {
Accept: "application/json"
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
success: function(data){
//alert(data);
data = JSON.parse(data);
if (isNaN(data.release_note)){
document.getElementById('note').value = parseInt(data.release_note.slice(0, -1)) + 1;
}
else{
document.getElementById('note').value = parseInt(data.release_note) + 1;
}
}
});
});
</script>
<script>
$('#comercial').change(function(){
document.getElementById('note').value = (document.getElementById('note').value + 'C');
});
</script>
<?php $this->end(); ?>
Это мой оператор создания таблицы
CREATE TABLE `inward_shipments` (
`release_note` varchar(10) NOT NULL,
`date` date DEFAULT NULL,
`supplier_id` int(11) DEFAULT NULL,
`shipping_method_id` int(11) DEFAULT NULL,
`freight_amount` float DEFAULT NULL,
`weight` float DEFAULT NULL,
`supplier_invoice_number` varchar(45) DEFAULT NULL,
`supplier_release_note` varchar(45) DEFAULT NULL,
`invoice_total` float DEFAULT NULL,
`comercial` tinyint(4) DEFAULT NULL,
`order_id` int(11) DEFAULT NULL,
`consignment_no` varchar(45) DEFAULT NULL,
`notes` varchar(255) DEFAULT NULL,
`dim_l` int(11) DEFAULT NULL,
`dim_w` int(11) DEFAULT NULL,
`dim_h` int(11) DEFAULT NULL,
`volume` float DEFAULT NULL,
`volumetric` float DEFAULT NULL,
`freight_invoice_no` varchar(45) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`USD_exch_rate` float DEFAULT NULL,
`freight_costs` float DEFAULT NULL,
`customs_costs` float DEFAULT NULL,
`freight_added` tinyint(4) DEFAULT NULL,
`certification_type` varchar(45) DEFAULT NULL,
`bank_charges` float DEFAULT NULL,
`other_charges` float DEFAULT NULL,
PRIMARY KEY (`release_note`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Это сообщение об ошибке, которое я всегда получаю, поскольку вы можете видеть, что release_note даже нет в инструкции Insert.







Я считаю, что это связано с тем, что вы не можете использовать VARCHAR в качестве первичного ключа в CakePHP, у вас могут быть только целые числа с автоматическим приращением и UUID CHAR (36).
В каком-то смысле примечания к выпуску увеличиваются автоматически, но в некоторых из них для рекламы стоит C на конце. Я решил это, просто сделав первичный ключ int и автоматически увеличив его.
@ndm Я изменил с 'release_note' => false на 'release_note' => true в файле сущности и избавился от disabled, и теперь он, кажется, работает, есть ли способ отключить поле для редактирования, и оно все еще работает?
Вместо этого вы можете отправить значение через отдельное скрытое поле и использовать отключенный ввод с другим именем только для отображения.
хорошо, это звучит как хороший способ, также просто попробовал другой способ с css pointer-events: none. Спасибо за вашу помощь.
Должна быть возможность использовать любой тип столбца для первичного ключа, CakePHP не должно заботиться, что, однако, не означает, что вы должны это делать, первичный ключ
VARCHAR, безусловно, имеет недостатки. Проблема, скорее всего, заключалась в том, что значение не было отправлено, учитывая, что ввод отключен, или, если вы что-то делали для отправки значения, его нельзя было назначить массово.