Getting a table column data as array with POST request in CakePHP - php

I have a form that has a table inside it and that table has a quantity column, I want to get the quantity of all products and put them in a quantity array in the controller, is there a way I can do that? For now, it doesn't work when I click Update Cart button. Here is my current code:
index page
<section class="section service border-top">
<div>
<?= $this->Form->create(null) ?>
<fieldset>
<?php if(isset($_SESSION['cart']) && !empty($_SESSION['cart'])){?>
<table id="cart-table" class="table table-bordered table-striped">
<thead>
<tr>
<th><?= 'Products' ?></th>
<th><?= 'Price'?></th>
<th><?= 'Quantity'?></th>
<th><?= 'Sub Total'?></th>
</tr>
</thead>
<tbody>
<?php foreach ($cart_items as $cart_item): ?>
<tr>
<td><?= $cart_item->name;?></td>
<td><span id="price"><?= "$ AU".$cart_item->price;?></span></td>
<td contenteditable='true'><?php echo $this->Form->number('quantity[]',['min'=>1, 'value'=>$cart_item->quantity]); ?></td>
<td><span id="total"><?php echo "$ AU".$cart_item->price * $cart_item->quantity?></span></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php }else{ ?>
You don't have any items in your cart. Add more?
<?php } ?>
</fieldset>
<?= $this->Form->button(__('Make a Payment'), ['class' => 'btn btn-success']) ?>
<?= $this->Form->button(__('Update Cart'), ['controller' => 'Carts', 'action' => 'updateCart'], ['class' => 'btn btn-success']) ?>
<?= $this->Form->end() ?>
<?= $this->Form->postLink(__('Clear Cart'), ['controller' => 'Carts', 'action' => 'clearCart'], ['class' => 'btn btn-danger', 'confirm' => __('Are you sure you want to clear your cart?')]) ?>
</section>
controller
public function updateCart()
{
if(isset($_SESSION['cart']) && !empty($_SESSION['cart'])){
if ($this->request->is('post')) {
$qty = $this->request->getData('quantity[]');
debug($this->request->getData('quantity'));
}
}
else{
$this->Flash->error(__("You don't have anything in your cart. Add more?"));
}
$this->redirect(['controller'=>'Carts','action' => 'index']);
}
Thank you

Related

Search for Products in the User View - Cakephp 3

Friends, I am displaying a user's profile along with the products registered by him. My relationships are correct. I can list all products as normal, along with user information. But my product search field in the user's view doesn't work.
This is my code detail_user.ctp
//user information only above. (Address, Telephone, etc.)
.
.
.
<h2 class="bd-title mt-2" id="content">Products Gallery</h2>
<div class="card mt-2 mb-2">
<div class="card-header">
<?= $this->Form->create('', ['type' => 'get']); ?>
<div class="input-group">
<?= $this->Form->control('keyword', array('class' => 'form-control','name'=> 'search','label' => false,'required' => true,));?>
<div class="input-group-append">
<?= $this->Form->button(__('Search')); ?>
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover">
<tbody>
<?php foreach ($user->products as $product): ?>
<td>
<p class="title mb-0"><?= h($product->name) ?> </p>
<var class="price text-muted">R$ <?= number_format($product->price);?></var>
</td>
<td> <br></td>
<td width="130">
<?= $this->Html->link(__('Open'), ['controller' => 'Produtos','action' => 'details_product','prefix' => false, $product->slug], array('class' => 'btn btn-primary')) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody></table>
</div> <!-- table-responsive .end// -->
</article>
And my method is like this:
public function detailUser($slug)
{
$keyword = $this->request->getQuery('keyword');
$query = $this->Users
->find()
->matching('Products', function(\Cake\ORM\Query $q) {
return $q->where(['name LIKE' => ('%'. $this->request->getQuery('keyword') . '%')]);
});
$usuario = $this->Users
->findBySlug($slug)
->contain(['Products', 'Groups'])
->firstOrFail();
$query = $this->Users->find('all');
$this->set('user', $user);
$this->set('query', $this->paginate());
}
I have difficulties to solve this method. At the moment, when I type the product name, the url changes, but the product is not searched.
I consulted the generated SQL and everything is correct, but it does not filter the word entered in the search field and also does not give an error.
I appreciate any comments!

Yii2: Nested Dynamic Form wbraganca added more fields

I am using wbragnaca dynamic form for yii2, add & remove button working properly on create, flawless. But when I update on the Instrument the nested form which is the Item is that when I click on the add button it adds 3 fields instead of just one.
Here is the form before I click on the Items - Statement button:
Instrument Form before
Here is after I click the add button on the Item:
Instrument Form after
Here is my database design:
DATABASE
Here is my code,
_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
/* #var $this yii\web\View */
/* #var $model app\models\Instrument */
/* #var $form yii\widgets\ActiveForm */
?>
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<div>
<?= $form->field($modelInstrument, 'name')->textInput(['maxlength' => true,'style'=>'width: 50%', 'placeholder'=>'Name'])->label(false) ?>
<?= $form->field($modelInstrument, 'description')->textArea(['rows' => '6', 'placeholder'=>'Description'])->label(false) ?>
</div>
<div class="padding-v-md">
<div class="line line-dashed"></div>
</div>
<br/>
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper',
'widgetBody' => '.container-items',
'widgetItem' => '.section-item',
'min' => 1,
'insertButton' => '.add-section',
'deleteButton' => '.remove-section',
'model' => $modelsSection[0],
'formId' => 'dynamic-form',
'formFields' => [
'name',
'description',
],
]); ?>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th >Sections</th>
<th style="width: 650px; height: 30px;">Items</th>
<th class="text-center" style="width: 30px; height: 30px;">
<button type="button" class="add-section btn btn-success btn-xs"><span class="glyphicon glyphicon-plus" style="font-size: 10px"></span></button>
</th>
</tr>
</thead>
<tbody class="container-items">
<?php foreach ($modelsSection as $indexSection => $modelSection): ?>
<tr class="section-item">
<td class="vcenter">
<?php
// necessary for update action.
if (! $modelSection->isNewRecord) {
echo Html::activeHiddenInput($modelSection, "[{$indexSection}]id");
}
?>
<?= $form->field($modelSection, "[{$indexSection}]name")->label(false)->textInput(['placeholder'=>"Name"]) ?>
<?= $form->field($modelSection, "[{$indexSection}]description")->label(false)->textArea(['rows' => '6', 'placeholder'=>'Description']) ?>
</td>
<td>
<?= $this->render('_form-item', [
'form' => $form,
'indexSection' => $indexSection,
'modelsItem' => $modelsItem[$indexSection],
]) ?>
</td>
<td class="text-center vcenter" style="width: 40px; verti">
<button type="button" class="remove-section btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus" style="font-size: 10px"></span></button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php DynamicFormWidget::end(); ?>
<div class="form-group">
<?= Html::submitButton($modelInstrument->isNewRecord ? 'Create' : 'Update', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
_form-item.php
<?php
use yii\helpers\Html;
use wbraganca\dynamicform\DynamicFormWidget;
?>
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_inner',
'widgetBody' => '.container-rooms',
'widgetItem' => '.room-item',
'min' => 1,
'insertButton' => '.add-item',
'deleteButton' => '.remove-item',
'model' => $modelsItem[0],
'formId' => 'dynamic-form',
'formFields' => [
'statement'
],
]); ?>
<table class="table table-bordered">
<thead>
<tr>
<th >Statements</th>
<th class="text-center">
<button type="button" class="add-item btn btn-success btn-xs"><span class="glyphicon glyphicon-plus" style="font-size: 10px"></span></button>
</th>
</tr>
</thead>
<tbody class="container-rooms">
<?php foreach ($modelsItem as $indexItem => $modelItem): ?>
<tr class="room-item">
<td class="vcenter">
<?php
// necessary for update action.
if (! $modelItem->isNewRecord) {
echo Html::activeHiddenInput($modelItem, "[{$indexSection}][{$indexItem}]id");
}
?>
<?= $form->field($modelItem, "[{$indexSection}][{$indexItem}]statement")->label(false)->textInput(['maxlength' => true]) ?>
</td>
<td class="text-center vcenter" style="width: 40px;">
<button type="button" class="remove-item btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus" style="font-size: 10px"></span></button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php DynamicFormWidget::end(); ?>
InstrumentController.php actionUpdate
public function actionUpdate($id)
{
$modelInstrument = $this->findModel($id);
$modelsSection = $modelInstrument->sections;
$modelsItem = [];
$oldItems = [];
if (!empty($modelsSection)) {
foreach ($modelsSection as $indexSection => $modelSection) {
$items = $modelSection->items;
$modelsItem[$indexSection] = $items;
$oldItems = ArrayHelper::merge(ArrayHelper::index($items, 'id'), $oldItems);
}
}
if ($modelInstrument->load(Yii::$app->request->post())) {
// reset
$modelsItem = [];
$oldSectionIDs = ArrayHelper::map($modelsSection, 'id', 'id');
$modelsSection = Model::createMultiple(Section::classname(), $modelsSection);
Model::loadMultiple($modelsSection, Yii::$app->request->post());
$deletedSectionIDs = array_diff($oldSectionIDs, array_filter(ArrayHelper::map($modelsSection, 'id', 'id')));
// validate Instrument and Section models
$valid = $modelInstrument->validate();
$valid = Model::validateMultiple($modelsSection) && $valid;
$itemsIDs = [];
if (isset($_POST['Item'][0][0])) {
foreach ($_POST['Item'] as $indexSection => $items) {
$itemsIDs = ArrayHelper::merge($itemsIDs, array_filter(ArrayHelper::getColumn($items, 'id')));
foreach ($items as $indexItem => $item) {
$data['Item'] = $item;
$modelItem = (isset($item['id']) && isset($oldItems[$item['id']])) ? $oldItems[$item['id']] : new Item;
$modelItem->load($data);
$modelsItem[$indexSection][$indexItem] = $modelItem;
$valid = $modelItem->validate();
}
}
}
$oldItemsIDs = ArrayHelper::getColumn($oldItems, 'id');
$deletedItemsIDs = array_diff($oldItemsIDs, $itemsIDs);
if ($valid) {
$transaction = Yii::$app->db->beginTransaction();
try {
if ($flag = $modelInstrument->save(false)) {
if (! empty($deletedItemsIDs)) {
Item::deleteAll(['id' => $deletedItemsIDs]);
}
if (! empty($deletedSectionIDs)) {
Section::deleteAll(['id' => $deletedSectionIDs]);
}
foreach ($modelsSection as $indexSection => $modelSection) {
if ($flag === false) {
break;
}
$modelSection->instrument_id = $modelInstrument->id;
if (!($flag = $modelSection->save(false))) {
break;
}
if (isset($modelsItem[$indexSection]) && is_array($modelsItem[$indexSection])) {
foreach ($modelsItem[$indexSection] as $indexItem => $modelItem) {
$modelItem->section_id = $modelSection->id;
if (!($flag = $modelItem->save(false))) {
break;
}
}
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $modelInstrument->id]);
} else {
$transaction->rollBack();
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('update', [
'modelInstrument' => $modelInstrument,
'modelsSection' => (empty($modelsSection)) ? [new Section] : $modelsSection,
'modelsItem' => (empty($modelsItem)) ? [[new Item]] : $modelsItem
]);
}
I copy the code from wbraganca's website. I change the code according to my need. But the update, just like I said when I want to update and add more Items on my Section the field adds 3 fields than just one.
I read the documentation and still I cant find the error.
Here is the Video to what happen when I click on the add button

Adding Data to the multiple column in laravel 5.7

Hi I am working on a project and I need to do some addition while working on a table.
like I have to fill the three fields and change the status to 2 using checkbox Array. I tried it all but with no luck. Kindly look into it and Let me know the changes I can Do.
My Model CustomerLoad.php is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CustomerLoad extends Model
{
protected $fillable = [
'driver_id',
'vehicle_id',
'company_id',
'customer_id',
'package_type',
'from',
'to',
'in_mile',
'weight',
'height',
'width',
'length',
'rate',
'duration_text',
'ticket_number',
'status_id'
];
public function status()
{
return $this->belongsTo('App\Status');
}
}
My Controller for creating the page is Like this
public function create()
{
$csloads = CustomerLoad::paginate(4);
$driver = Driver::pluck('name', 'id')->all();
$vehicle = Vehicle::pluck('vin', 'id')->all();
$company = Company::pluck('name', 'id')->all();
return view('customerload.create', compact('csloads', 'driver', 'vehicle', 'company'));
}
for storing it
public function updatecsloads(Request $request)
{
if(isset($request->update_all) && !empty($request->checkBoxArray)){
$csloads = CustomerLoad::findOrFail($request->checkBoxArray);
foreach($csloads as $csload){
$input = $request->all();
dd($input);
// $csload->update($input);
}
// return redirect()->back();
// } else {
// return redirect()->back();
}
}
My View is like
<div class="card">
<div class="card-header card-header-rose card-header-text">
<div class="card-ttle">
<h4 class="card-text">Allocate Loads</h4>
</div>
</div>
<div class="card-body">
{!! Form::model(['method' => 'PATCH', 'action' => ['CustomerLoadsController#updatecsloads']]) !!}
<div class='form-group'>
{!! Form::select('checkBoxArray', ['' => 'Allocate'], null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>''])!!}
</div>
<div class='form-group'>
{!! Form::submit('Allocate Loads', ['class'=>'btn btn-rose pull-right']) !!}
</div>
#if(count($csloads) > 0)
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th><input type="checkbox" id="options"></th>
<th>Driver Name</th>
<th>Company Name</th>
<th>Vehicle Vin Number</th>
<th>Origin</th>
<th>Destination</th>
<th>Package Type</th>
<th>Dimensions</th>
<th>Weight</th>
</tr>
</thead>
<tbody>
#foreach($csloads as $csload)
#if($csload->status_id == 1)
<tr>
<td>{‌{$csload->id}}</td>
<td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="{‌{$csload->status ? $csload->status->id == 2 : $csload->status->id == 1}}"></td>
<td>{!! Form::select('driver_id', ['' => 'Choose Driver Name'] + $driver, null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>'exampleFormControlSelect1'])!!}</td>
<td>{!! Form::select('company_id', ['' => 'Choose Company Name'] + $company, null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>'exampleFormControlSelect1'])!!}</td>
<td>{!! Form::select('vehicle_id', ['' => 'Choose Vehicle Vin Number'] + $vehicle, null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>'exampleFormControlSelect1'])!!}</td>
<td>{‌{$csload->from}}</td>
<td>{‌{$csload->to}}</td>
<td>{‌{$csload->package_type}}</td>
<td>{‌{$csload->length}}x{‌{$csload->width}}x{‌{$csload->height}}</td>
<td>{‌{$csload->weight}}</td>
</tr>
#endif
#endforeach
</tbody>
</table>
</div>
#else
<h1 class="text-center">No Loads Found</h1>
#endif
{!! Form::close() !!}
</div>
</div>
</div>
I am struck in the project kindly answer the question as soon as you can I shall be really obliged.
Thanks in advance
From Munish Rana
Love your Work
change 'method' => 'PATCH' to 'POST'
and add {{ method_field('PATCH') }} to form field like this
<form method="POST" action="your url" >
{{csrf_field()}}
{{ method_field('PATCH') }}
</form>

How to set a different label for tabular input - Yii2

I have followed this guide http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html to build a tabular input. But in my case, I want to add a different label for each input. How can I do that?
Update action:
public function actionUpdate()
{
$emailModel = EMAIL::find()->indexBy('ID')->all();
if (Model::loadMultiple($emailModel, Yii::$app->request->post()) && Model::validateMultiple($emailModel)) {
foreach ($emailModel as $email) {
$email->save(false);
}
return $this->redirect('update');
}
return $this->render('update', ['emailModel' => $emailModel]);
}
Update View
<?php $form = ActiveForm::begin(); ?>
<?php foreach ($emailModel as $index => $email) { ?>
<?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true])->label(false) ?>
<?php } ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
I'm on learning Yii2. Thank you.
Changing the label for multiple models is the same as for one model.
1) To retrieve it from attributeLabels() or generate automatically based on according database column name (in case it's ActiveRecord and there is no according entry in attributeLabels()) just omit ->label(false) call:
<?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true]) ?>
2) To apply custom label just for this form:
<?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true])->label('Your custom label') ?>
3) To have different label for each $model in a set just create helper function and call it in the loop:
function getCustomLabel($model, $index)
{
$number = $index + 1;
return "Content for model number $number";
}
<?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true])->label(getCustomLabel($model, $index)) ?>
Check the official docs:
yii\widgets\ActiveField label()
Creating forms (ActiveField)
Add label(label name) used as per Tabular Input
<?php $form = ActiveForm::begin(); ?>
<?php foreach ($emailModel as $index => $email) { ?>
<?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true])->label('Email '.$index+1) ?>
<?php } ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
Refer the Docs
Yii2 Active Field

Problems with view rendering

I have a page with list of users in admin panel, it has a view with bootstrap table (users list). Today I noticed that it renders only half or less number of users. After refreshing the page the point in which it stops is different user (might be on 250's user or 1000's). The data from controller is full and solid, I checked it with printing users array. Here the picture of ending the view:
And the code inside table:
<? foreach ($items as $item): ?>
<tr>
<td><strong><?= $item->id; ?></strong></td>
<td>
<?= $item->username ?>
</td>
<td>
<?= $item->name ?>
</td>
<td>
<?= $item->email ?>
</td>
<td>
<?= $item->phone ?>
</td>
<td>
<?= $item->remark ?>
</td>
<td>
<span style="color: <?= $item->validated ? 'green' : 'gray' ?>"><?= $item->validated ? 'Активирован' : 'Не активирован'?></span>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Действия <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="<?= Route::url('admin', array(
'controller' => $model->object_name(),
'action' => 'edit',
'id' => $item->id
)) ?>">Редактировать</a></li>
<li><a href="<?= Route::url('admin', array(
'controller' => $model->object_name(),
'action' => 'delete',
'id' => $item->id
)) ?>">Удалить</a></li>
</ul>
</div>
</td>
</tr>
<?php endforeach ?>
Error log is empty
UPD When I try to open this page on the iphone, it starts to load it and the throws error "Operation could not be completed" error 303
Something goes wrong when you call $item->validated for your 250'th user.
<?= $item->validated ? 'green' : 'gray' ?>"><?= $item->validated ? 'Активирован' : 'Не активирован'?>
Check your php logs first and find your error.

Categories