How to update multiple inputs in Laravel? I have two tables: Order and Detail_Order. Here's my controller to create multiple inputs.
public function store($id_trip, Request $request){
$order = new Order();
$order->id_trip = $id_trip;
$order->id_users = Auth::guard('operator')->user()->id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = Auth::guard('operator')->user()->id_users;
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'address' => $request->address[$key],
'phone_number' => $request->phone_number[$key]
]);
}
}
I tried to update it, but I don't know how to update the Detail_order. Here's my update controller :
public function update($id_order, $id_trip, Request $request){
$order = Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->first();
$order->id_trip = $request->id_trip;
$order->id_users = Auth::guard('operator')->user()->id_users;
$order->save();
$detail = Detail_Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->get();
if(count($request->id_seat) > 0){
for($i = 0; $i < count($request->id_seat); $i++){
$detail[$i]->id_trip = $order->id_trip;
$detail[$i]->id_seat = $request->id_seat[$i];
$detail[$i]->id_order = $pesanan->id_order;
$detail[$i]->passenger_name = $request->passenger_name[$i];
$detail[$i]->address = $request->address[$i];
$detail[$i]->phone_number = $request->phone_number[$i];
$detail[$i]->save();
}
}
session()->flash('flash_success', 'Data has been updated');
return redirect('/order');
}
after $order->save(); line you can do something like this....
if it is work good .. if not you can comment below . i will give you solution...
$order->save();
$detail = Detail_Order::where('order_id', $order->id)->get();
if(count($request->id_seat) > 0){
for($i = 0; $i < count($request->id_seat); $i++){
$detail[$i]->order_id = $order->id;
$detail[$i]->id_seat = $request->id_seat[$i],
$detail[$i]->passenger_name = $request->passenger_name[$i];
$detail[$i]->save();
}
}
I am creating one API. In that I want to show buyers info, urls for their files/ images, and count in response. I have 3 tables buyers(PK: buyers_id), filedocs(FK: buyers_id), give_credit_transaction_master(FK: buyers_id). In those tables common column is buyers_id.
CODE
public function index()
{
$filedocsObj = FileDoc::with(['relBuyers'])->where('is_active','1')->get();
//return $filedocsCount;
$info = [];
// $profile_urls=[];
// $aadhar_urls=[];
// $pan_urls=[];
// $transaction_count=[];
// $info = array();
for($i = 0; $i < count($filedocsObj); $i++){
$buyer = FileDoc::Join('buyers', 'file_docs.buyers_id', '=', 'buyers.buyers_id')
->where('file_docs.buyers_id',$filedocsObj[$i]->buyers_id)
->select(
'buyers.buyers_id',
'buyers.buyers_name',
'buyers.buyers_address',
'buyers.buyers_contact_number',
'buyers.buyers_aadhar_number',
'buyers.buyers_pan_number',
'file_docs.buyers_profile_image',
'file_docs.buyers_aadhar_file',
'file_docs.buyers_pan_file',
)
->first();
// $info = $buyer->toArray();
array_push($info, [
'info' => $buyer
]);
// $info[] = $buyer;
$existProfile = Storage::disk('local')->exists('public/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image);
if (isset($filedocsObj[$i]->buyers_profile_image) && $existProfile) {
// $profile_urls[$i] = Storage::disk('public')->url('/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image);
array_push($info, [
'profile_url' => Storage::disk('public')->url('/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image)
]);
//$info[] = Storage::disk('public')->url('/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image);
}
else
{
// $profile_urls[$i]="";
array_push($info, [
'profile_url' => ''
]);
// $info[] = "";
}
$existAadhar = Storage::disk('local')->exists('public/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file);
if (isset($filedocsObj[$i]->buyers_aadhar_file) && $existAadhar) {
//$aadhar_urls[$i] = Storage::disk('public')->url('/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file);
array_push($info, [
'aadhar_url' => Storage::disk('public')->url('/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file)
]);
// $info[] = Storage::disk('public')->url('/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file);
}
$existPan = Storage::disk('local')->exists('public/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file);
if (isset($filedocsObj[$i]->buyers_pan_file) && $existPan) {
//$pan_urls[$i] = Storage::disk('public')->url('/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file);
array_push($info, [
'pan_url' => Storage::disk('public')->url('/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file)
]);
//$info[] = Storage::disk('public')->url('/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file);
}
$buyerTransactions = GiveCreditTransactionMaster::where('buyers_id',$filedocsObj[$i]->buyers_id)->get();
array_push($info, [
'transaction_count' => count($buyerTransactions)
]);
// $transaction_count[$i] = count($buyerTransactions);
// $resultSet = array_merge($info,$profile_urls,$aadhar_urls,$pan_urls,$transaction_count);
}
return $this->sendResponse($info, 'Buyers retrieved successfully.');
// return $this->sendResponse($resultSet, 'Buyers retrieved successfully.');
// return $this->sendResponse(array("Info" => $filedocs->toArray(),"profile_path" => $profile_urls, "aadhar_urls" => $aadhar_urls, "pan_urls" => $pan_urls, "transactionCountArray" => $transactionCountArray), 'Buyers retrieved successfully.');
}
In above code, I have taken one array info in which I am pushing query result buyer , iteration result profile_url, aadhar_url, pan_url, and another query result counts transaction_count. And returning info array as response.
MY API response:
{
"success": true,
"data": [
{
"info": {
"buyers_id": 2,
"buyers_name": "uuu",
"buyers_address": "dfgfgf",
"buyers_contact_number": "8986665576",
"buyers_aadhar_number": "654654654545",
"buyers_pan_number": "tytyr43242",
"buyers_profile_image": "2_B_profile_lady_profile.png",
"buyers_aadhar_file": "2_B_aadhar_aadhar_card_image.png",
"buyers_pan_file": "2_B_pan_pan_image.jpg"
}
},
{
"profile_url": "http://localhost/storage/uploads/profile_images/2_B_profile_lady_profile.png"
},
{
"aadhar_url": "http://localhost/storage/uploads/aadhar_files/2_B_aadhar_aadhar_card_image.png"
},
{
"pan_url": "http://localhost/storage/uploads/pan_files/2_B_pan_pan_image.jpg"
},
{
"transaction_count": 2
},
{
"info": {
"buyers_id": 28,
"buyers_name": "lili",
"buyers_address": "hjkhkdfgf",
"buyers_contact_number": "7856564656",
"buyers_aadhar_number": "343435353545",
"buyers_pan_number": "trtre34343",
"buyers_profile_image": "28_B_profile_test_profile.png",
"buyers_aadhar_file": "28_B_aadhar_test_aadhar.jpg",
"buyers_pan_file": "28_B_pan_test_pan.jpg"
}
},
{
"profile_url": "http://localhost/storage/uploads/profile_images/28_B_profile_test_profile.png"
},
{
"aadhar_url": "http://localhost/storage/uploads/aadhar_files/28_B_aadhar_test_aadhar.jpg"
},
{
"pan_url": "http://localhost/storage/uploads/pan_files/28_B_pan_test_pan.jpg"
},
{
"transaction_count": 0
}
],
"message": "Buyers retrieved successfully."
}
But in above response I am getting info of particular buyer separately than profile_url, aadhar_url, pan_url, transaction_count. Also profile_url, aadhar_url, pan_url, transaction_count this are getting separately.
I want all parameters(info,profile_url, aadhar_url, pan_url, transaction_count) of one buyer should come in one {}. How can I get that type of response?
I tried a lot using array_push, array_merge etc. But not getting requied response.
Please help. Thanks in advance.
This will help you with your desired response. I have manged your function. make it try and let me know if it helps you thanks
public
function index()
{
$filedocsObj = FileDoc::with(['relBuyers'])->where('is_active', '1')->get();
//return $filedocsCount;
$info = [];
// $profile_urls=[];
// $aadhar_urls=[];
// $pan_urls=[];
// $transaction_count=[];
// $info = array();
foreach ($filedocsObj as $index => $filedocsObjInfo) {
$buyer = FileDoc::Join('buyers', 'file_docs.buyers_id', '=', 'buyers.buyers_id')
->where('file_docs.buyers_id', $filedocsObjInfo->buyers_id)
->select(
'buyers.buyers_id',
'buyers.buyers_name',
'buyers.buyers_address',
'buyers.buyers_contact_number',
'buyers.buyers_aadhar_number',
'buyers.buyers_pan_number',
'file_docs.buyers_profile_image',
'file_docs.buyers_aadhar_file',
'file_docs.buyers_pan_file',
)
->first();
// $info = $buyer->toArray();
$info[$index]['info'] = $buyer;
// $info[] = $buyer;
$existProfile = Storage::disk('local')->exists('public/uploads/profile_images/' . $filedocsObjInfo->buyers_profile_image);
if (isset($filedocsObjInfo->buyers_profile_image) && $existProfile) {
$info[$index]['profile_url'] = Storage::disk('public')->url('/uploads/profile_images/' . $filedocsObjInfo->buyers_profile_image);
} else {
$info[$index]['profile_url'] = '';
}
$existAadhar = Storage::disk('local')->exists('public/uploads/aadhar_files/' . $filedocsObjInfo->buyers_aadhar_file);
if (isset($filedocsObjInfo->buyers_aadhar_file) && $existAadhar) {
$info[$index]['aadhar_url'] = Storage::disk('public')->url('/uploads/aadhar_files/' . $filedocsObjInfo->buyers_aadhar_file);
}
$existPan = Storage::disk('local')->exists('public/uploads/pan_files/' . $filedocsObjInfo->buyers_pan_file);
if (isset($filedocsObjInfo->buyers_pan_file) && $existPan) {
$info[$index]['pan_url'] = Storage::disk('public')->url('/uploads/pan_files/' . $filedocsObjInfo->buyers_pan_file);
}
$buyerTransactions = GiveCreditTransactionMaster::where('buyers_id', $filedocsObjInfo->buyers_id)->get();
$info[$index]['transaction_count'] = count($buyerTransactions);
// $transaction_count[$i] = count($buyerTransactions);
// $resultSet = array_merge($info,$profile_urls,$aadhar_urls,$pan_urls,$transaction_count);
}
return $this->sendResponse($info, 'Buyers retrieved successfully.');
// return $this->sendResponse($resultSet, 'Buyers retrieved successfully.');
// return $this->sendResponse(array("Info" => $filedocs->toArray(),"profile_path" => $profile_urls, "aadhar_urls" => $aadhar_urls, "pan_urls" => $pan_urls, "transactionCountArray" => $transactionCountArray), 'Buyers retrieved successfully.');
}
on PHP the following solution might work.
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
Try and let me know.
When you use an array_merge try json_decode your value like above.
I am new to cakephp.Below the number being bold is the time the data is being created and code to validate .My problem is to validate the data should between 8 hours not more that using Model. is there any wrong in my code?
sample data=L02A-180129-1215-A
The code to find the table based on data
public function sa01() {
$trv_no = $this->data[$this->alias]['TRV_No_01'];
$line_no = intval(substr($trv_no, 1, 2));
$table_name = 'Ticket_L' . $line_no;
$this->Ticket->setSource($table_name);
$this->Ticket->recursive =-1;
code for validation
Batch_time is a column name for the table
$time = $this->Ticket->find('all',array('conditions' => array('Ticket.Batch_Time >=' => date('Y-m-d H:i:s', strtotime('-8 hour')))));
if(empty($time))
{
$table_name = 'Ticket_L0';
$this->Ticket->setSource($table_name);
//$ticket = $this->Ticket->find('first', array('conditions' => array('Ticket.TRV_No' => $trv_no)));
$time = $this->Ticket->find('all',array('conditions' => array('Ticket.Batch_Time >=' => date('Y-m-d H:i:s', strtotime('-8 hour')))));
if(empty($time)) { return false; } else { return true; }
}
else
{ return true; }
}
I have used dynamic form widget. The form fields are shown in the image below. As you can see there is a check box named cancel. What I want is if the cancel check box is clicked, It will only requires the check number and will allow the rest to be empty. Without using dynamic form I can easily implement this using when and whenClient validators since I can get exactly the name of the checkbox.
The problem here is that the dynamic form generates this kind of name series for the checkboxes...
TblDvBub[0][is_cancelled][]
TblDvBub[1][is_cancelled][]
TblDvBub[2][is_cancelled][]
I think you could extract the name of is_cancelled checkbox using 'attribute.name' from 'whenClient' => 'function(attribute, value){}' argument. console.log that 'attribute' - there must be an object with 'name' property - there you may get the number (use regex) of current TblDvBub.
By the way why do you use multiple is_cancelled[] field - doesn't it already belong to particular TblDvBub subarray?
1) In the form, you must override fieldClass
<?php $form = ActiveForm::begin([
'fieldClass' => 'backend\widgets\ActiveField'
]); ?>
2) To override the method
<?php
class ActiveField extends \yii\widgets\ActiveField
{
protected function getClientOptions()
{
$attribute = Html::getAttributeName($this->attribute);
if (!in_array($attribute, $this->model->activeAttributes(), true)) {
return [];
}
$enableClientValidation = $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation;
$enableAjaxValidation = $this->enableAjaxValidation || $this->enableAjaxValidation === null && $this->form->enableAjaxValidation;
if ($enableClientValidation) {
$validators = [];
foreach ($this->model->getActiveValidators($attribute) as $validator) {
/* #var $validator \yii\validators\Validator */
$js = $validator->clientValidateAttribute($this->model, $attribute, $this->form->getView());
if ($validator->enableClientValidation && $js != '') {
if ($validator->whenClient !== null) {
$js = "if (({$validator->whenClient})(attribute, value, '{$this->form->id}')) { $js }";
}
$validators[] = $js;
}
}
}
if (!$enableAjaxValidation && (!$enableClientValidation || empty($validators))) {
return [];
}
$options = [];
$inputID = $this->getInputId();
$options['id'] = $inputID;
$options['name'] = $this->attribute;
$options['container'] = isset($this->selectors['container']) ? $this->selectors['container'] : ".field-$inputID";
$options['input'] = isset($this->selectors['input']) ? $this->selectors['input'] : "#$inputID";
if (isset($this->selectors['error'])) {
$options['error'] = $this->selectors['error'];
} elseif (isset($this->errorOptions['class'])) {
$options['error'] = '.' . implode('.', preg_split('/\s+/', $this->errorOptions['class'], -1, PREG_SPLIT_NO_EMPTY));
} else {
$options['error'] = isset($this->errorOptions['tag']) ? $this->errorOptions['tag'] : 'span';
}
$options['encodeError'] = !isset($this->errorOptions['encode']) || $this->errorOptions['encode'];
if ($enableAjaxValidation) {
$options['enableAjaxValidation'] = true;
}
foreach (['validateOnChange', 'validateOnBlur', 'validateOnType', 'validationDelay'] as $name) {
$options[$name] = $this->$name === null ? $this->form->$name : $this->$name;
}
if (!empty($validators)) {
$options['validate'] = new JsExpression("function (attribute, value, messages, deferred, \$form) {" . implode('', $validators) . '}');
}
// only get the options that are different from the default ones (set in yii.activeForm.js)
return array_diff_assoc($options, [
'validateOnChange' => true,
'validateOnBlur' => true,
'validateOnType' => false,
'validationDelay' => 500,
'encodeError' => true,
'error' => '.help-block',
]);
}
}
?>
3) Validation can be used
<?php
'whenClient' => "function(attribute, value, form) {
$("form# " + form + " > attribute")
}"
?>
Im having problem with rebinding grid with Json object….
Im trying to create custom delete button…
So far I have Jquery function: Gets an ID of selected column (username) and call controller action “UserDetails”
Delete button:
$("#DeleteUser").click(function () {
if (id != "") {
var answer = confirm("Delete user " + id)
if (answer) {
$.ajax({
type: "POST",
url: "/Admin/UserDetails",
data: "deleteName=" + id,
success: function (data) {
}
});
}
} else {
$("#erorMessage").html("First you must select user you whant to delete!");
}
});
This is action controller UserDetails(string startsWith, string deleteName)
[GridAction]
public ActionResult UserDetails(string startsWith, string deleteName)
{ // Custom search...
if (!string.IsNullOrEmpty(startsWith))
{
return GetSearchUserResult(startsWith);
}
if (!string.IsNullOrEmpty(deleteName))
{
TblUserDetails user = db.TblUserDetails.Single(a => a.TblUser.userName == deleteName);
try
{
TblUser userToDelete = db.TblUser.Single(a => a.userId == user.TblUser.userId);
db.DeleteObject(user);
db.DeleteObject(userToDelete);
db.SaveChanges();
Membership.DeleteUser(deleteName);
List<UserDto> retModelData = new List<UserDto>();
//GetAllUsers() returns a List<UserDto> of users.
retModelData = GetAllUsers();
var model = new GridModel
{
Data = retModelData,
Total = GetAllUsers().Count()
};
return View(model);
}
catch
{
return View(new GridModel());
}
}
else
{
var user = GetAllUsers();
return View(new GridModel(user));
}
}
So far everything is working OK. But can I bind my grid with these Json data and how???
This is my Json result that I want to bind with grid...
And here is my grid:
#(Html.Telerik().Grid<App.Web.Models.UserDto>()
.Name("Grid")
.DataKeys(key =>
{
key.Add(a => a.Id);
})
.Columns(column =>
{
column.Bound(a => a.Username).Filterable(false);
column.Bound(a => a.FirstName).Filterable(false);
column.Bound(a => a.LastName).Filterable(false);
column.Bound(a => a.Email).Filterable(false);
})
.DetailView(detailView => detailView.ClientTemplate(
"<table id='DetailTable'><tbody><tr class='UserRow'><td class='Tbllable'><b>First name</b></td><td><#= FirstName #></td>"
+ "<td></td><td></td>"
+ "</tr><tr><td class='Tbllable'><b>Last name</b></td>"
+ "<td><#= LastName #></td>"
+ "<td id='Roles'></td><td id='Operations'></td>"
+ "</tr><tr><td class='Tbllable'><b>Username</b></td><td><#= Username #></td></tr><tr><td class='Tbllable'><b>Address</b></td>"
+ "<td><#= Address #></td></tr><tr><td class='Tbllable'><b>Email</b></td><td><#= Email #></td></tr><tr><td class='Tbllable'><b>Birth date</b></td>"
+ "<td></td></tr><tr><td class='Tbllable'><b>Registration date</b></td><td></td></tr><tr><td class='Tbllable'><b>Phone number</b></td>"
+ "<td><#= PhoneNumberHome #></td></tr><tr><td class='Tbllable'><b>Mobile number</b></td><td><#= PhoneNumberMobile #></td></tr></tbody></table>"
))
//.EnableCustomBinding(true)
.DataBinding(bind => bind.Ajax().Select("UserDetails", "Admin", new { startsWith = ViewBag.startsWith }))
.Pageable(paging =>
paging.PageSize(12)
.Style(GridPagerStyles.NextPreviousAndInput)
.Position(GridPagerPosition.Bottom)
)
.ClientEvents(e => e
.OnRowDataBound("Expand")
.OnRowSelect("select")
.OnLoad("replaceConfirmation")
)
.RowAction(row =>
{
if (row.Index == 0)
{
row.DetailRow.Expanded = true;
}
})
.Editable(editing => editing.Mode(GridEditMode.PopUp))
.Selectable()
.Sortable()
)