Display Remove and Edit Item button in Order summary in Onepage Checkout page Magento2 - magento

I want to display remove and Edit Icon in order summary section in checkout page, I have tried below changes:
/magento_demo/vendor/magento/module-checkout/view/frontend/web/template/summary/item/details.html
I have added Edit / Delete links like this:
<div class="primary">
<a data-bind="attr: {href: getConfigUrl($parent.item_id),title: $t('Edit item')}" class="action edit">
<span data-bind="i18n: 'Edit'"></span>
</a>
</div>
<div class="secondary">
<a href="#" data-bind="attr: {'data-post': getDataPost($parent.item_id),title: $t('Delete item')}" class="action delete">
<span data-bind="i18n: 'Remove'"></span>
</a>
</div>
In
/magento_demo/vendor/magento/module-checkout/view/frontend/web/js/view/summary/item/details.js
I have done below changes:
define(
[
'uiComponent',
'mage/url',
'Magento_Customer/js/customer-data',
'jquery',
'ko',
'underscore',
'sidebar',
'mage/translate'
],
function (Component,url,customerData,$,ko, _) {
"use strict";
return Component.extend({
defaults: {
template: 'Magento_Checkout/summary/item/details'
},
getValue: function(quoteItem) {
var itemId = elem.data('cart-item'),
itemQty = elem.data('item-qty');
return quoteItem.name;
},
getDataPost: function(itemId) {
console.log(itemId);
var itemsData = window.checkoutConfig.quoteItemData;
var obj = {};
var obj = {
data: {}
};
itemsData.forEach(function (item) {
if(item.item_id == itemId) {
var mainlinkUrl = url.build('checkout/cart/delete/');
var baseUrl = url.build('checkout/cart/');
console.log(mainlinkUrl);
obj.action = mainlinkUrl;
obj.data.id= item.item_id;
obj.data.uenc = btoa(baseUrl);
}
});
return JSON.stringify(obj);
},
getConfigUrl: function(itemId) {
var itemsData = window.checkoutConfig.quoteItemData;
var configUrl = null;
var mainlinkUrl = url.build('checkout/cart/configure');
var linkUrl;
itemsData.forEach(function (item) {
var itm_id = item.item_id;
var product_id = item.product.entity_id;
if(item.item_id == itemId) {
linkUrl = mainlinkUrl+"/id/"+itm_id+"/product_id/"+product_id;
}
});
if(linkUrl != null) {
return linkUrl;
}
else {
return '';
}
}
});
}
);
But when I click on delete button, it just redirecting to cart page but not deleting product, what can be the issue here.

Related

Laravel 8 filter data with ajax

I want to filter the data in my table. I have seen many tutorials online but do not understand. I found a tutorial that seemed very complicated to me. I just want to use a controller and view. Constants are used in that tutorial and the filter data is static but I don't want to use it and my filter data is dynamic. Help me out as a newbie.
The code of the tutorial is given here
app/Constants/GlobalConstants
<?php
namespace App\Constants;
class GlobalConstants {
const USER_TYPE_FRONTEND = "frontend";
const USER_TYPE_BACKEND = "backend";
const ALL = 'All';
const LIST_TYPE = [self::USER_TYPE_FRONTEND, self::USER_TYPE_BACKEND];
const LIST_COUNTRIES = ["Canada", "Uganda", "Malaysia", "Finland", "Spain", "Norway"];
const SALARY_RANGE = ['401762', '85295', '287072', '456969', '354165'];
}
App/User
public static function getUsers($search_keyword, $country, $sort_by, $range) {
$users = DB::table('users');
if($search_keyword && !empty($search_keyword)) {
$users->where(function($q) use ($search_keyword) {
$q->where('users.fname', 'like', "%{$search_keyword}%")
->orWhere('users.lname', 'like', "%{$search_keyword}%");
});
}
// Filter By Country
if($country && $country!= GlobalConstants::ALL) {
$users = $users->where('users.country', $country);
}
// Filter By Type
if($sort_by) {
$sort_by = lcfirst($sort_by);
if($sort_by == GlobalConstants::USER_TYPE_FRONTEND) {
$users = $users->where('users.type', $sort_by);
} else if($sort_by == GlobalConstants::USER_TYPE_BACKEND) {
$users = $users->where('users.type', $sort_by);
}
}
// Filter By Salaries
if ($range && $range != GlobalConstants::ALL) {
$users = $users->where('users.salary', $range);
}
return $users->paginate(PER_PAGE_LIMIT);
}
App/Http/Controllers/HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Constants\GlobalConstants;
class HomeController extends Controller
{
public function index() {
$users = User::getUsers('', GlobalConstants::ALL, GlobalConstants::ALL, GlobalConstants::ALL);
return view('home')->with('users', $users);
}
public function getMoreUsers(Request $request) {
$query = $request->search_query;
$country = $request->country;
$sort_by = $request->sort_by;
$range = $request->range;
if($request->ajax()) {
$users = User::getUsers($query, $country, $sort_by, $range);
return view('pages.user_data', compact('users'))->render();
}
}
}
view code
#foreach($users as $key)
<div class="card">
<div class="card-header">
<img src="{{ asset('assets/images/dev.png') }}" alt="" />
</div>
<div class="card-body">
<span class="tag tag-pink">{{ $key->type }}</span>
<hr>
<span class="tag tag-salary">Salary: {{ $key->salary }}</span>
<h4>{{ $key->email }}</h4>
<p>
{{ $key->address }}
</p>
<h4>Country: {{ $key->country }}</h4>
<div class="user">
#php
$user=App\User::find($key->id)
#endphp
<img src="{{ asset('assets/images/user-3.jpg') }}" alt="" />
<div class="key-info">
<h5>{{ $user['fullname'] }}</h5>
<small>{{ date('d.m.Y H:i:s', strtotime($key->created_at)) }}</small>
</div>
</div>
</div>
</div>
#endforeach
<script>
$(document).ready(function() {
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
getMoreUsers(page);
});
$('#search').on('keyup', function() {
$value = $(this).val();
getMoreUsers(1);
});
$('#country').on('change', function() {
getMoreUsers();
});
$('#sort_by').on('change', function (e) {
getMoreUsers();
});
$('#salary_range').on('change', function (e) {
getMoreUsers();
});
});
function getMoreUsers(page) {
var search = $('#search').val();
// Search on based of country
var selectedCountry = $("#country option:selected").val();
// Search on based of type
var selectedType = $("#sort_by option:selected").val();
// Search on based of salary
var selectedRange = $("#salary_range option:selected").val();
$.ajax({
type: "GET",
data: {
'search_query':search,
'country': selectedCountry,
'sort_by': selectedType,
'range': selectedRange
},
url: "{{ route('users.get-more-users') }}" + "?page=" + page,
success:function(data) {
$('#user_data').html(data);
}
});
}
</script>
public function create(Request $request)
{
$doctors = Doctors::all();
$query = doctors_slots::query();
'services.','consultation.')
// ->get();
if($request->ajax()){
$doctors_slots = $query->where(['doc_id'=>$request->doctors])->get();
return response()->json(compact('doctors_slot'));
}
$doctors_slots = $query->get();
return view('Admin.booking.add_booking',compact('doctors','doctors_slots'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#doctors").on('change', function() {
var doctors = $(this).val();
$.ajax({
url: "{{ route('booking') }}",
type: "GET",
data: {
'doctors': doctors
},
success: function(data) {
var doctors_slots = data.doctors_slots;
var html = '';
if (doctors_slots.length > 0) {
for (let i = 0; i < doctors_slots.length; i++) {
html += '<option value="' + doctors_slots[i][
'available_time_start'
] + '' + doctors_slots[i]['available_time_end'] + '">\
' + doctors_slots[i]['available_time_start'] + ' To\
' + doctors_slots[i]['available_time_end'] + '\
</option>';
}
} else {
html += '<option>No Data Found</option>';
}
$('#option').html(html);
}
});
});
});
</script>

Dynamically Binding the the Oracle jet switcher slot to the oracle jet add and remove tab(Make switcher slot dynamic in oracle jet)

I want to make tab switcher auto decide the slot for the switcher but when I am trying to make it dynamic with the help of observable no data is showing the tab content area until I write the slot area statically. With observable variable, the slot is not getting the selected Slot value.
Please check how I can do this.
slot = [[selectedSlot]] //using for the slot value in html
this.selectedSlot = ko.observable('settings');
<div id="tabbardemo">
<oj-dialog class="tab-dialog hidden" id="tabDialog" dialog-title="Tab data">
<div slot="body">
<oj-form-layout>
<oj-input-text id="t1" value="{{newTabTitle}}" label-hint="Title"></oj-input-text>
</oj-form-layout>
</div>
<div slot="footer">
<oj-button id="idOK" on-oj-action="[[addTab]]">OK</oj-button>
<oj-button id="idCancel" on-oj-action="[[closeDialog]]">Cancel</oj-button>
</div>
</oj-dialog>
<oj-button id="addTab" on-oj-action="[[openDialog]]">Add Tab</oj-button>
<br/>
<br/>
<oj-tab-bar contextmenu="tabmenu" id="hnavlist" selection="{{selectedItem}}" current-item="{{currentItem}}" edge="top" data="[[dataProvider]]"
on-oj-remove="[[onRemove]]">
<template slot="itemTemplate" data-oj-as="item">
<li class="oj-removable" :class="[[{'oj-disabled' : item.data.disabled}]]">
<a href="#">
<oj-bind-text value="[[item.data.name]]"></oj-bind-text>
</a>
</li>
</template>
<oj-menu slot="contextMenu" class="hidden" aria-label="Actions">
<oj-option data-oj-command="oj-tabbar-remove">
Removable
</oj-option>
</oj-menu>
</oj-tab-bar>
<oj-switcher value="[[selectedItem]]">
<div slot="[[selectedSlot]]"
id="home-tab-panel"
role="tabpanel"
aria-labelledby="home-tab">
<div class="demo-tab-content-style">
<h2>Home page content area</h2>
</div>
</div>
<div slot="tools"
id="tools-tab-panel"
role="tabpanel"
aria-labelledby="tools-tab">
<div class="demo-tab-content-style">
<h1>Tools Area</h1>
</div>
</div>
<div slot="base"
id="base-tab-panel"
role="tabpanel"
aria-labelledby="ba`enter code here`se-tab">
<div class="demo-tab-content-style">
<h1>Base Tab</h1>
</div>
</div>
</oj-switcher>
<br>
<div>
<p class="bold">Last selected list item:
<span id="results">
<oj-bind-text value="[[selectedItem]]"></oj-bind-text>
</span>
</p>
</div>
</div>
JS code below
require(['ojs/ojcontext',
'knockout',
'ojs/ojbootstrap',
'ojs/ojarraydataprovider',
'ojs/ojknockout',
'ojs/ojnavigationlist',
'ojs/ojconveyorbelt',
'ojs/ojdialog',
'ojs/ojbutton',
'ojs/ojinputtext',
'ojs/ojformlayout',
'ojs/ojswitcher',
],
function (Context, ko, Bootstrap, ArrayDataProvider) { // this callback gets executed when all required modules are loaded
function ViewModel() {
this.data = ko.observableArray([{
name: 'Settings',
id: 'settings'
},
{
name: 'Tools',
id: 'tools'
},
{
name: 'Base',
id: 'base'
}
]);
this.selectedSlot = ko.observable('settings'); //Sepecifically mentioned to show what it is the objective
this.dataProvider = new ArrayDataProvider(this.data, { keyAttributes: 'id' });
this.selectedItem = ko.observable('settings');
this.currentItem = ko.observable();
this.tabCount = 0;
this.newTabTitle = ko.observable();
this.delete = (function (id) {
var hnavlist = document.getElementById('hnavlist');
var items = this.data();
for (var i = 0; i < items.length; i++) {
if (items[i].id === id) {
this.data.splice(i, 1);
Context.getContext(hnavlist)
.getBusyContext()
.whenReady()
.then(function () {
hnavlist.focus();
});
break;
}
}
}).bind(this);
this.onRemove = (function (event) {
this.delete(event.detail.key);
event.preventDefault();
event.stopPropagation();
}).bind(this);
this.openDialog = (function () {
this.tabCount += 1;
this.newTabTitle('Tab ' + this.tabCount);
document.getElementById('tabDialog').open();
}).bind(this);
this.closeDialog = function () {
document.getElementById('tabDialog').close();
};
this.addTab = (function () {
var title = this.newTabTitle();
var tabid = 'tid' + this.tabCount;
this.data.push({
name: title,
id: tabid
});
this.closeDialog();
}).bind(this);
}
Bootstrap.whenDocumentReady().then(function () {
ko.applyBindings(new ViewModel(), document.getElementById('tabbardemo'));
});
}
);
It is a bit complex to understand when you copy from JET cookbook. You have done almost everything right. Just make the following changes:
1) Remove this:
Bootstrap.whenDocumentReady().then(function () {
ko.applyBindings(new ViewModel(), document.getElementById('tabbardemo'));
});
Why? The bootstrapping is required once per application, which is done inside your main.js file.
2) Replace require by define
Why? Require block is again maintained in main.js, where your required modules are pre-loaded. All subsequent viewModels have define block
3) Return an instance of your ViewModel
define([
... Your imports
],
function (Context, ko, Bootstrap, ArrayDataProvider) { // this callback gets executed when all required modules are loaded
function ViewModel() {
// Your code
}
return ViewModel;
});

How to insert infinite scroll to Laravel Project

Am very new to Jquery and Ajax being used in laravel and been trying to implement infinite scroll to my project and i have no idea where to start
The Controller:
$books= DB::table('books')->where('status', 'post')->orderBy('created_at', 'DESC')->paginate(15);
if ($books->isEmpty())
{
$books= null;
return view('landingpage')->withBooks($books);
}
return view('landingpage')->withBooks($books);
The view
#if ($books== null)
<center><p class="paragraph"> Be the first to share your shopping experience here</p></center>
#else
<div class="row mt-0"> <div class="infinite-scroll"> #foreach ($books as $item)
<div class="col-lg-4 mt-3">
<p class="paragraph"> <sup><i class="fa fa-quote-left" style="font-size:5px" aria-hidden="true"></i></sup>{{$item->title}}<sup><i class="fa fa-quote-right" style="font-size:5px" aria-hidden="true"></i></sup> </p>
<img src="../images/{{$item->rate}}.png" style="width:50%" alt="Image">
<h2 style="font-size:18px">{{$item->firstname}} {{$item->lastname}}</h2> </div>#endforeach </div>{{$books->links()}}</div>
#endif
The JS
<script type="text/javascript">
$('ul.pagination').hide();
$(function() {
$('.infinite-scroll').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="images/loading.gif" alt="Loading..." />',
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.infinite-scroll',
callback: function() {
$('ul.pagination').remove();
}
});
});
Any help will be grately appreciated
I use ajax for infinate scroll this is example :
Method for view :
public function index(){
return view('index');
}
Method for get data wia ajax:
public function ajaxData(Request $request)
{
$post_query = Trends::query()
->where('is_offer', '!=', 1)
->where('direct_to', null)
->orderBy('id', 'desc')
->paginate(12);
$data['post_list'] = $post_query;
if ($data['post_list']->count() > 0) {
$ajax_data['post'] = true;
$ajax_data['next_url'] = $data['post_list']->nextPageUrl();
$ajax_data['next_data'] = $data['post_list'];
} else {
$ajax_data['html'] = false;
$ajax_data['post'] = false;
$ajax_data['next_url'] = $data['post_list']->nextPageUrl();
}
return response()->json($ajax_data);
}
And this is my script in blade
var loaddataUrl = '{!! route('explore-ajax-data',array_merge(request()->all())) !!}';
var nextData = true;
$(document.body).on('touchmove', onExploreScroll); // for mobile
$(window).on('scroll', onExploreScroll);
function onExploreScroll() {
if ($(window).scrollTop() >= ($(document).height() - $(window).height()) * 0.9) {
if (nextData) {
nextData = false;
loadMoreData();
}
}
}
function loadMoreData() {
$.ajax({
type: 'GET',
url: loaddataUrl,
success: function (data) {
if (data.next_url) {
loaddataUrl = data.next_url;
console.log(data.next_data);
nextData = true;
} else {
nextData = false;
}
},
error: function (data) {
nextData = true;
}
})
}
route(explore-ajax-data) map to public function ajaxData(Request $request)
my routes are :
// this will display home page or home view
Route::get('home', 'HomeController#index')->name('home');
// this is for ajax request.
Route::get('ajax/explore-data', 'HomeController#ajaxData')->name('explore-ajax-data');
link of tutorial

Vue2 component rendering on ajax response

I have created a component that reacts to this template:
<table-sort index="job.job_id"></table-sort>
However, when I get this template from a ajax response and add it to the DOM. It doesn't recognize it as a Vue component. How do I render this component?
Here is my component:
Vue.component('table-sort', {
name: 'table-sort',
template: `
<div class="table-sort" :data-index="index">
<i v-on:click="sortTable($event)" direction="ASC" class="fa fa-caret-up"></i>
<i v-on:click="sortTable($event)" direction="DESC" class="fa fa-caret-down"></i>
</div>
`,
props: {
index: {
type: String,
required: true,
},
},
methods: {
sortTable: function ($event) {
const self = $event.target;
const index = this.index;
const direction = self.getAttribute('direction');
let filters = Url.getQueryParameters();
filters.sort = index;
filters.direction = direction;
filters.page = 1;
const url = Url.getUrlWithoutQueryString();
const newUrl = Url.appendParamsToUrl(filters, url);
Url.redirect(newUrl);
},
},
});
Here is how I call the code to generate the table:
var ajaxTable = new AjaxTable({
name: 'jobs',
request: inputs,
container: '#job-table',
fields: fields,
});
Here is the code that appends the template:
public async drawTable() {
this.table = $(`<table class="table table-striped table-bordered table-hover table-condensed"><thead><tr id="header"></tr></thead><tbody></tbody></table>`);
this.count = $(`<div class="count pull-left"></div>`);
this.pagination = $(`<div class="pagination pull-right"></div>`);
this.fields.map((field: ColumnData) => {
let out = `<th>${field.title}`;
if (!!field.sort) {
out += ` <table-sort index="${field.sort}"></table-sort>`;
}
out += `</th>`;
this.table.find('#header').append(out);
});
this.container.append(this.table, this.count, this.pagination);
}

update model with ajax in razor

i write this code with ajax to delete some info after that i update my updateAjax div with ajax for refreshing content and this view have masterpage.in picture u see what happen.
this is my code
#using Common.UsersManagement.Entities;
#model IEnumerable<VwUser>
#{
Layout = "~/Views/Shared/Master.cshtml";
}
<form id="userForm">
<div id="updateAjax">
#if (string.IsNullOrWhiteSpace(ViewBag.MessageResult) == false)
{
<div class="#ViewBag.cssClass">
#Html.Label(ViewBag.MessageResult as string)
</div>
<br />
}
<table class="table" cellspacing="0">
#foreach (VwUser Item in Model)
{
<tr class="#(Item.IsActive ? "tRow" : "Disable-tRow")">
<td class="tbody">
<input type="checkbox" id="#Item.Id" name="selected" value="#Item.FullName"/></td>
<td class="tbody">#Item.FullName</td>
<td class="tbody">#Item.Post</td>
<td class="tbody">#Item.Education</td>
</tr>
}
</table>
</div>
<br />
<br />
<div class="btnContainer">
delete
<br />
<br />
</div>
<script>
$(function () {
// function for delet info and update #updateAjax div
$("#DeleteUser").click(function (event) {
var list = [];
$('#userForm input:checked').each(function () {
list.push(this.id);
});
$.ajax({
url: '#Url.Action("DeleteUser", "UserManagement")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "html",
traditional: true,
data: JSON.stringify(list),
success: function (data, textStatus, jqXHR) {
$('#updateAjax').html(data);
// window.location.reload()
},
error: function (data) {
//$('#updateAjax').html(data);
window.location.reload()
}
}); //end ajax
});});
</script>
</form>
this my controller code
public ActionResult View1()
{
ViewBag.PageTittle = "user list";
ViewBag.FormTittle = "user list";
SetUserManagement();
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View(Result.Data);
}
else
{
return View(new VwUser());
}
}
public ActionResult DeleteUser(string[] userId)
{
SetUserManagement();
string message = "", CssClass = ""; ;
foreach (string item in userId)
{
//TODO:show Message
var Result = userManagement.DeleteUser(int.Parse(item));
if (Result.Mode != Common.Extensions.ActionResultMode.Successfully)
{
var messageResult = XmlReader.FindMessagekey(Result.Mode.ToString());
message += messageResult.MessageContent + "<br/>";
CssClass = messageResult.cssClass;
}
}
if (string.IsNullOrEmpty(message))
{
SetMessage(Common.Extensions.ActionResultMode.Successfully.ToString());
}
else
{
ViewBag.MessageResult = message;
ViewBag.cssClass = CssClass;
}
//
{
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View("~/Views/UserManagement/View1.cshtml", Result.Data);
}
else
{
return View("~/Views/UserManagement/View1.cshtml", new VwUser());
}
}
}
It looks to me that your view ViewUserList.cshtml is using a Layout that would either be set through Layout or through the _ViewStart.cshtml file. Make sure you're not using any of these.
For disabling the use of your Layout, you could take a look at this question. Or just set Layout = null

Resources