Invalid shipping method in magento 1.8.1?
When my cart value in 950 - 999 INR but below 950 or above 999 working fine?
One page controller code is below.
Kindly help me
onePageController.php
<?php
require_once Mage::getModuleDir('controllers', 'Mage_Checkout').DS.'OnepageController.php';
class Webly_QuickCheckout_OnepageController extends Mage_Checkout_OnepageController
{
public function saveBillingAction()
{
if ($this->_expireAjax()) {
return;
}
if ($this->getRequest()->isPost()) {
// $postData = $this->getRequest()->getPost('billing', array());
// $data = $this->_filterPostData($postData);
$data = $this->getRequest()->getPost('billing', array());
$customerAddressId = $this->getRequest()->getPost('billing_address_id', false);
if (isset($data['email'])) {
$data['email'] = trim($data['email']);
}
$data['use_for_shipping'] = 1;
$result = $this->getOnepage()->saveBilling($data, $customerAddressId);
if (!isset($result['error'])) {
if (!isset($result['error'])) {
if ($this->getOnepage()->getQuote()->isVirtual()) {
$result['goto_section'] = 'payment';
$result['update_section'] = array(
'name' => 'payment-method',
'html' => $this->_getPaymentMethodsHtml()
);
} elseif (isset($data['use_for_shipping']) && $data['use_for_shipping'] == 1) {
$quote =$this->getOnepage()->getQuote();
$quote->getBaseGrandTotal();
$result = $this->getOnepage()->saveShipping($data, $customerAddressId);
if ($quote->getBaseGrandTotal() < 1000) {
$method = 'inchoo_shipping_fixed';
} else {
$method = 'inchoo_shipping_free';
}
// $method = 'flatrate_flatrate';
$result = $this->getOnepage()->saveShippingMethod($method);
Mage::getSingleton('checkout/type_onepage')->getQuote()->getShippingAddress()-> setShippingMethod($method)->save();
$result['update_section'] = array(
'name' => 'payment-method',
'html' => $this->_getPaymentMethodsHtml()
);
$result['goto_section'] = 'payment';
} else {
$result['goto_section'] = 'shipping';
}
}
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
}
}
Related
I'm building a profile page for users of my app (nextjs 12) and when I add authentication middleware it works fine locally but when deployed to the production server (apache shared hosting with nodejs v 14 installed) it throws error 500
my node version installed locally is v16.16.0 could that affect this issue?
any suggestions?
profile.tsx:
const ProfileEditor = () => {
const dispatch = useDispatch();
const {
profile,
profileLogin,
user
} = useSelector((state: RootState) => state.Auth);
useEffect(() => {
dispatch(FetchProfileAsync());
}, []);
const [preview, setPreview] = useState < string > ();
const handleFormSubmit = async(values: any, e: any) => {
dispatch(UpdateProfileAsync(values as any));
};
let initialValues = {
image: profile ? .image ? .full_path,
first_name: profile ? .first_name,
last_name: profile ? .last_name,
email: profile ? .email,
phone: profile ? .phone,
};
const FILE_SIZE = 160 * 1024;
const SUPPORTED_FORMATS = ['image/jpg', 'image/png'];
const checkoutSchema = yup.object().shape({
image: yup.mixed().required('A file is required'),
// .test('fileSize', 'File too large', (value) => value && value.size <= FILE_SIZE)
// .test('fileFormat', 'Unsupported Format', (value) => value && SUPPORTED_FORMATS.includes(value.type)),
first_name: yup.string().required('required'),
last_name: yup.string().required('required'),
email: yup.string().email('invalid email').required('required'),
phone: yup.string().required('required'),
});
return ( <
CustomerDashboardLayout >
<
DashboardPageHeader icon = {
Person
}
title = 'Edit Profile'
navigation = { < CustomerDashboardNavigation / >
}
/>
<
Card1 >
<
Formik enableReinitialize initialValues = {
initialValues
}
validationSchema = {
checkoutSchema
}
onSubmit = {
(values: any, e: any) => handleFormSubmit(values, e)
} >
{
({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
setFieldValue
}) => ( <
form onSubmit = {
handleSubmit
} >
<
FlexBox alignItems = 'flex-end'
mb = {
3
} >
<
Avatar src = {
preview ? ? user ? .image ? .full_path
}
sx = {
{
height: 64,
width: 64
}
}
alt = 'user image' / >
{ /* <img src={user?.image?.full_path} height={100} width={100} alt='fdss' /> */ }
<
Box ml = {-2.5
} >
<
label htmlFor = 'profile-image' >
<
Button component = 'span'
color = 'secondary'
sx = {
{
bgcolor: 'grey.300',
height: 'auto',
p: '8px',
borderRadius: '50%',
}
} >
<
CameraEnhance fontSize = 'small' / >
<
/Button> <
/label> <
/Box> <
Box display = 'none' >
<
input name = 'image'
onChange = {
(newFile: any) => {
setFieldValue('image', newFile.currentTarget.files[0]);
FileToBase64(newFile.currentTarget.files[0] as any).then((res) => setPreview(res));
}
}
id = 'profile-image'
accept = 'image/*'
type = 'file' /
>
<
/Box> <
/FlexBox>
<
Box mb = {
4
} >
<
Grid container spacing = {
3
} >
<
Grid item md = {
6
}
xs = {
12
} >
<
ETextField mb = {
1.5
}
name = 'first_name'
label = 'First Name'
placeholder = 'First Name'
variant = 'outlined'
size = 'small'
fullWidth onBlur = {
handleBlur
}
onChange = {
handleChange
}
value = {
values.first_name || ''
}
error = {!!touched.first_name && !!errors.first_name
}
helperText = {
touched.first_name && errors.first_name
}
/> <
/Grid> <
Grid item md = {
6
}
xs = {
12
} >
<
ETextField mb = {
1.5
}
name = 'last_name'
label = 'Last Name'
placeholder = 'Last Name'
variant = 'outlined'
size = 'small'
fullWidth onBlur = {
handleBlur
}
onChange = {
handleChange
}
value = {
values.last_name || ''
}
error = {!!touched.last_name && !!errors.last_name
}
helperText = {
touched.last_name && errors.last_name
}
/> <
/Grid> <
Grid item md = {
6
}
xs = {
12
} >
<
ETextField mb = {
1.5
}
name = 'email'
label = 'Email'
placeholder = 'exmple#mail.com'
variant = 'outlined'
size = 'small'
type = 'email'
fullWidth onBlur = {
handleBlur
}
onChange = {
handleChange
}
value = {
values.email || ''
}
error = {!!touched.email && !!errors.email
}
helperText = {
touched.email && errors.email
}
/> <
/Grid> <
Grid item md = {
6
}
xs = {
12
} >
<
ETextField mb = {
1.5
}
name = 'phone'
label = 'Phone'
placeholder = '09********'
variant = 'outlined'
size = 'small'
fullWidth onBlur = {
handleBlur
}
onChange = {
handleChange
}
value = {
values.phone || ''
}
error = {!!touched.phone && !!errors.phone
}
helperText = {
touched.phone && errors.phone
}
/> <
/Grid> <
/Grid> <
/Box>
<
ELoadingButton type = 'submit'
variant = 'contained'
loading = {
profileLogin === 'loading'
}
buttonText = 'Save Changes'
loadingPosition = 'start'
fullWidth = {
true
}
color = 'primary' /
>
<
/form>
)
} <
/Formik> <
/Card1> <
/CustomerDashboardLayout>
);
};
export default ProfileEditor;
middlware.tsx
// eslint-disable-next-line #next/next/no-server-import-in-page
import { NextResponse } from 'next/server';
// eslint-disable-next-line #next/next/no-server-import-in-page
import type { NextRequest } from 'next/server';
import { KEY_TOKEN_COOKIE } from 'src/constants';
const middleware = (request: NextRequest, response: NextResponse) => {
const token = request?.cookies[KEY_TOKEN_COOKIE];
if (!token) return NextResponse.rewrite(new URL('/error/auth', request.url));
};
export default middleware;
I'm trying to generate more than one thousand pdf files using surveyPDF.
The problem is that i can generate only 80 pdf files...
I'm passing an array with more than 1000 pdf to generate.
Code :
query.map(async items => {
const { generatePdf } = await import("~/lib/survey");
const filename = kebabCase(
`${campaign.title} - ${items.employee.fullName.toLowerCase()} -${moment().format("DD/MM/YYYY - HH:mm")} `
);
return generatePdf(campaign.template.body, items, filename, 210, 297);
});
The code which generate each pdfs :
import autoTable from "jspdf-autotable";
import { SurveyPDF, CommentBrick, CompositeBrick, PdfBrick, TextBrick } from "survey-pdf";
import { format } from "~/utils/date";
class AutoTableBrick extends PdfBrick {
constructor(question, controller, rect, options) {
super(question, controller, rect);
this.margins = {
top: controller.margins.top,
bottom: controller.margins.bot,
right: 30,
left: 30,
};
this.options = options;
}
renderInteractive() {
if (this.controller.doc.lastAutoTable && !this.options.isFirstQuestion) {
this.options.startY = this.yTop;
}
autoTable(this.controller.doc, {
head: [
[
{
content: this.question.title,
colSpan: 2,
styles: { fillColor: "#5b9bd5" },
},
],
],
margin: { ...this.margins },
styles: { fillColor: "#fff", lineWidth: 1, lineColor: "#5b9bd5", minCellWidth: 190 },
alternateRowStyles: { fillColor: "#bdd6ee" },
...this.options,
});
}
}
export async function generatePdf(json, data, filename, pdfWidth, pdfHeight) {
if (!json) {
return Promise.reject("Invalid json for pdf export");
}
for (const page of json.pages) {
page.readOnly = true;
}
const surveyPDF = new SurveyPDF(json, {
fontSize: 11,
format: [pdfWidth, pdfHeight],
commercial: true,
textFieldRenderAs: "multiLine",
});
surveyPDF.showQuestionNumbers = "off";
surveyPDF.storeOthersAsComment = false;
//TODO This does not work well with dynamic dropdown, bug declared
// surveyPDF.mode = "display";
surveyPDF.mergeData({ ...data, _: {} });
surveyPDF.onRenderQuestion.add(function(survey, options) {
const { bricks, question } = options;
if (question.getType() === "comment" && question.value && bricks.length > 0) {
for (const brick of bricks) {
if (brick.value) {
brick.value = question.value.replace(/\t/g, " ");
}
if (brick instanceof CompositeBrick) {
const { bricks } = brick;
for (const brick of bricks) {
if (brick instanceof CommentBrick) {
brick.value = question.value.replace(/\t/g, " ");
}
}
}
}
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
bricks,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "multipletext") {
const body = [];
let extraRows = 0;
let rows = question.getRows();
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < rows[i].length; j++) {
let { title, value, inputType } = rows[i][j];
if (inputType === "date") {
value = format(value);
}
if (typeof value === "string" && value.length > 0) {
const valueEstRows = value.match(/.{1,70}/g).length;
if (valueEstRows > 1) {
extraRows += valueEstRows;
}
}
body.push([title, value || "N/A"]);
}
}
//TODO Use SurveyHelper helperDoc do calculate the height of the auto table
const startY = point.yTop;
const height = 21.5 * (body.length + 1) + 8.5 * extraRows;
const isFirstQuestion = question.title === question.parent.questions[0].title;
options.bricks = [
new AutoTableBrick(question, controller, SurveyHelper.createRect(point, bricks[0].width, height), {
startY,
body,
isFirstQuestion,
}),
];
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "text") {
//Draw question background
const { default: backImage } = await import("~/public/assets/images/block.png");
const backWidth = SurveyHelper.getPageAvailableWidth(controller);
const backHeight = SurveyHelper.pxToPt(100);
const imageBackBrick = SurveyHelper.createImageFlat(point, null, controller, backImage, backWidth, backHeight);
options.bricks = [imageBackBrick];
point.xLeft += controller.unitWidth;
point.yTop += controller.unitHeight;
const oldFontSize = controller.fontSize;
const titleBrick = await SurveyHelper.createTitleFlat(point, question, controller);
controller.fontSize = oldFontSize;
titleBrick.unfold()[0]["textColor"] = "#6a6772";
options.bricks.push(titleBrick);
//Draw text question text field border
let { default: textFieldImage } = await import("~/public/assets/images/input.png");
let textFieldPoint = SurveyHelper.createPoint(imageBackBrick);
textFieldPoint.xLeft += controller.unitWidth;
textFieldPoint.yTop -= controller.unitHeight * 3.3;
let textFieldWidth = imageBackBrick.width - controller.unitWidth * 2;
let textFieldHeight = controller.unitHeight * 2;
let imageTextFieldBrick = SurveyHelper.createImageFlat(
textFieldPoint,
null,
controller,
textFieldImage,
textFieldWidth,
textFieldHeight
);
options.bricks.push(imageTextFieldBrick);
textFieldPoint.xLeft += controller.unitWidth / 2;
textFieldPoint.yTop += controller.unitHeight / 2;
let textFieldValue = question.value || "";
if (textFieldValue.length > 90) {
textFieldValue = textFieldValue.substring(0, 95) + "...";
}
const textFieldBrick = await SurveyHelper.createBoldTextFlat(
textFieldPoint,
question,
controller,
textFieldValue
);
controller.fontSize = oldFontSize;
textFieldBrick.unfold()[0]["textColor"] = "#EFF8FF";
options.bricks.push(textFieldBrick);
}
});
surveyPDF.onRenderQuestion.add(async function(survey, options) {
const {
point,
question,
controller,
module: { SurveyHelper },
} = options;
if (question.getType() === "radiogroup" || question.getType() === "rating") {
options.bricks = [];
const oldFontSize = controller.fontSize;
const titleLocation = question.hasTitle ? question.getTitleLocation() : "hidden";
let fieldPoint;
if (["hidden", "matrix"].includes(titleLocation)) {
fieldPoint = SurveyHelper.clone(point);
} else {
const titleBrick = await SurveyHelper.createTitleFlat(point, question, controller);
titleBrick.xLeft += controller.unitWidth;
titleBrick.yTop += controller.unitHeight * 2;
controller.fontSize = oldFontSize;
titleBrick.unfold()[0]["textColor"] = "#6a6772";
options.bricks.push(titleBrick);
fieldPoint = SurveyHelper.createPoint(titleBrick);
fieldPoint.yTop += controller.unitHeight * 1.3;
}
//Draw checkbox question items field
const { default: itemEmptyImage } = await import("~/public/assets/images/unchecked.png");
const { default: itemFilledImage } = await import("~/public/assets/images/checked.png");
const itemSide = controller.unitWidth;
let imageItemBrick;
const choices = question.getType() === "rating" ? question.visibleRateValues : question.visibleChoices;
for (const choice of choices) {
const isItemSelected =
question.getType() === "rating" ? question.value === choice.value : choice === question.selectedItem;
imageItemBrick = SurveyHelper.createImageFlat(
fieldPoint,
null,
controller,
isItemSelected ? itemFilledImage : itemEmptyImage,
itemSide,
itemSide
);
options.bricks.push(imageItemBrick);
const textPoint = SurveyHelper.clone(fieldPoint);
textPoint.xLeft += itemSide + controller.unitWidth / 2;
textPoint.yTop += itemSide / 12;
const itemValue = choice.locText.renderedHtml;
const checkboxTextBrick = await SurveyHelper.createTextFlat(
textPoint,
question,
controller,
itemValue,
TextBrick
);
checkboxTextBrick.unfold()[0]["textColor"] = "#6a6772";
fieldPoint.yTop = imageItemBrick.yBot + SurveyHelper.GAP_BETWEEN_ROWS * controller.unitHeight;
options.bricks.push(checkboxTextBrick);
}
}
});
surveyPDF.onRenderFooter.add(function(survey, canvas) {
canvas.drawText({
text: canvas.pageNumber + "/" + canvas.countPages,
fontSize: 10,
horizontalAlign: "right",
margins: {
right: 12,
},
});
});
return await surveyPDF.raw(`./pdf/${filename}.pdf`);
}
The error :
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
I have already try to increase the node memory using $env:NODE_OPTIONS="--max-old-space-size=8192"
I have a key array of objects which user have for days and their timings for their shop i.e
user A -
{
"name" : "shop1",
"timings" : [
{
"Monday" : "10am to 7pm"
},
{
"Thursday" : "Closed"
},
{
"Friday" : "9am to 6pm"
},
{
"Sunday" : "Closed"
},
{
"Wednesday" : "10am to 7pm"
},
{
"Tuesday" : "10am to 7pm"
},
{
"Saturday" : "10am to 7pm"
}
]}
Now I need to show these timing by days in frontend i.e
Monday-Saturday:9am to 7pm, Thursday,Sunday: Closed
So far I've tried to loop them and searched all days which are closed i.e
function filterByValue(array, string) {
return array.filter(o =>
Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
}
let closedDays = filterByValue(element.timings, 'Closed')
console.log("whtt",closedDays); // [{name: 'Lea', country: 'Italy'}]
let res = closedDays.map(x => Object.keys(x)[0]);
but for open days I can't figure out any suitable solution which can be used here. It would be a great help if you suggest something
const timings = [{"Monday": "10am to 7pm"}, {"Thursday": "Closed"}, {"Friday": "9am to 6pm"}, {"Sunday": "Closed"}, {"Wednesday": "10am to 7pm"}, {"Tuesday": "10am to 7pm"}, {"Saturday": "10am to 7pm"}];
const weekDaysInOrder = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
//Step1 little change list of objects
const newTimings = changeTimingsStructure(timings);
let obj = {}
sortTimings(newTimings).forEach(el => {
if (el.timing in obj) {
const maxIndex = Math.max(...obj[el.timing].map(el => el.indexOfDay));
if (maxIndex + 1 < el.indexOfDay && el.timing !== 'Closed') {
obj = pushToObjectArr(el.timing + '-v2', el, obj);
} else {
obj = pushToObjectArr(el.timing, el, obj);
}
} else {
obj = pushToObjectArr(el.timing, el, obj);
}
})
displayTimings(obj);
function changeTimingsStructure(timings) {
const newTimings = [];
timings.forEach(day => {
const dayName = Object.keys(day)[0]
const timing = day[dayName];
newTimings.push({
day: dayName,
timing,
indexOfDay: weekDaysInOrder.findIndex(dayInWeek => dayInWeek === dayName)
})
})
return newTimings;
}
function sortTimings(timings) {
return timings.sort(((a, b) => a.indexOfDay - b.indexOfDay));
}
function pushToObjectArr(key, el, obj) {
if (key in obj) {
obj[key].push(el);
} else {
obj[key] = [el]
}
return obj
}
function displayTimings(obj) {
let closedText = '';
for (const groupOfDays in obj) {
if (groupOfDays !== 'Closed') {
if (obj[groupOfDays].length > 1) {
console.log(`${obj[groupOfDays][0].day} - ${obj[groupOfDays][obj[groupOfDays].length - 1].day}: ${groupOfDays}`);
} else {
console.log(`${obj[groupOfDays][0].day}: ${obj[groupOfDays][0].timing}`);
}
} else {
closedText = `${obj[groupOfDays].map(dayObj => dayObj.day).join(', ')}: Closed`;
}
}
console.log(closedText);
}
Try this, final output:
Here I have created this utility in order to format the input as per your expected output.
let data = {name:'shop1',timings:[{Monday:'10am to 7pm'},{Thursday:'Closed'},{Friday:'9am to 6pm'},{Sunday:'Closed'},{Wednesday:'10am to 7pm'},{Tuesday:'10am to 7pm'},{Saturday:'10am to 7pm'}]};
const formatData = data => {
return data.reduce(
(result, d) => {
const value = Object.values(d)[0];
const key = Object.keys(d)[0];
if (value === 'Closed') {
result.closed.days.push(key);
if (!result.closed.values) {
result.closed.value = value;
}
} else {
result.open.days.push(key);
result.open.timings.push(value);
}
return result;
},
{
closed: { days: [], value: '' },
open: { days: [], timings: [] },
}
);
};
const formattedData = formatData(data.timings);
const formatTimings = timings => {
const formattedTimings= timings.reduce((result, time) => {
const times = time
.split('to')
.map(t => parseInt(t.replace(/\D+/g, '')))
.filter(Boolean);
result.from.push(times[0]);
result.to.push(times[1]);
return result
}, {from :[], to: []});
return `${Math.min(...formattedTimings.from)}am to ${Math.max(...formattedTimings.to)}pm`
};
const openDaysTimings = formatTimings(formattedData.open.timings);
const displayTimings = (days, time) => {
return `${days.join(", ")}: ${time}`
}
console.log(displayTimings(formattedData.closed.days, formattedData.closed.value));
console.log(displayTimings(formattedData.open.days, openDaysTimings));
I have been working on a project to generate configurable dashboards.
so i have to generate schema dynamically based on an api request. is there any way to do that?
it will be very helpful if there is any working example!
There's an asyncModule function for this scenario. You can check example below:
const fetch = require('node-fetch');
const Funnels = require('Funnels');
asyncModule(async () => {
const funnels = await (await fetch('http://your-api-endpoint/funnels')).json();
class Funnel {
constructor({ title, steps }) {
this.title = title;
this.steps = steps;
}
get transformedSteps() {
return Object.keys(this.steps).map((key, index) => {
const value = this.steps[key];
let where = null
if (value[0] === PAGE_VIEW_EVENT) {
if (value.length === 1) {
where = `event = '${value[0]}'`
} else {
where = `event = '${value[0]}' AND page_title = '${value[1]}'`
}
} else {
where = `event = 'se' AND se_category = '${value[0]}' AND se_action = '${value[1]}'`
}
return {
name: key,
eventsView: {
sql: () => `select * from (${eventsSQl}) WHERE ${where}`
},
timeToConvert: index > 0 ? '30 day' : null
}
});
}
get config() {
return {
userId: {
sql: () => `user_id`
},
time: {
sql: () => `time`
},
steps: this.transformedSteps
}
}
}
funnels.forEach((funnel) => {
const funnelObject = new Funnel(funnel);
cube(funnelObject.title, {
extends: Funnels.eventFunnel(funnelObject.config),
preAggregations: {
main: {
type: `originalSql`,
}
}
});
});
})
More info: https://cube.dev/docs/schema-execution-environment#async-module
Can anyone help me in the implementation of nested set behavior https://github.com/creocoder/yii2-nested-sets with Yii2 Menu Widget?
Basically I want the hierarchical sidebar navigation menu like this http://www.surtex-instruments.co.uk/surgical/general-surgical-instruments
Thanks.
In your Model class define this functions:
public static function getTree($selected, $search)
{
$categories = Categories::find()->orderBy('lft')->asArray()->all();
$tree = [];
$index = 0;
foreach ($categories as $category) {
if ($category['parent_category_id'] === NULL) {
$tree[$index]['text'] = $category['category_' . Yii::$app->language];
if ($search) {
$tree[$index]['href'] = Url::to(['products', 'category' => $category['category_id'], 'search' => $search, 'string' => $category['category_' . Yii::$app->language]]);
} else {
$tree[$index]['href'] = Url::to(['products', 'category' => $category['category_id'], 'string' => $category['category_' . Yii::$app->language] ]);
}
$tree[$index]['id'] = $category['category_id'];
if ($selected) {
if ($selected['category_id'] == $category['category_id']) {
$tree[$index]['state']['selected'] = true;
}
if ($selected['lft'] >= $category['lft'] && $selected['rgt'] <= $category['rgt']) {
$tree[$index]['state']['expanded'] = true;
}
}
if ($category['lft'] + 1 != $category['rgt']) {
Categories::getNodes($tree[$index], $categories, $selected, $search);
}
$index++;
}
}
return $tree;
}
private static function getNodes(&$tree, $categories, $selected, $search)
{
$index = 0;
foreach ($categories as $category) {
if ($tree['id'] == $category['parent_category_id']) {
$tree['nodes'][$index]['text'] = $category['category_' . Yii::$app->language];
if ($search) {
$tree['nodes'][$index]['href'] = Url::to(['products', 'category' => $category['category_id'], 'search' => $search, 'string' => $category['category_' . Yii::$app->language]]);
} else {
$tree['nodes'][$index]['href'] = Url::to(['products', 'category' => $category['category_id'], 'string' => $category['category_' . Yii::$app->language]]);
}
$tree['nodes'][$index]['id'] = $category['category_id'];
if ($selected) {
if ($selected['category_id'] == $category['category_id']) {
$tree['nodes'][$index]['state']['selected'] = true;
}
if ($selected['lft'] >= $category['lft'] && $selected['rgt'] <= $category['rgt']) {
$tree['nodes'][$index]['state']['expanded'] = true;
}
}
if ($category['lft'] + 1 != $category['rgt']) {
Categories::getNodes($tree['nodes'][$index], $categories, $selected, $search);
}
$index++;
}
}
}
and use this extension execut/yii2-widget-bootstraptreeview
In the controller file get the menu like this:
public function actionProducts($category = false)
{
...
$data = Categories::getTree($category,'');
In your view file
<?php
...
use execut\widget\TreeView;
...
$onSelect = new JsExpression(<<<JS
function (undefined, item) {
window.location.href = item.href;
}
JS
);
?>
<?= TreeView::widget([
'data' => $data,
'template' => TreeView::TEMPLATE_SIMPLE,
'clientOptions' => [
'onNodeSelected' => $onSelect,
'onhoverColor' => "#fff",
'enableLinks' => true,
'borderColor' => '#fff',
'collapseIcon' => 'fa fa-angle-down',
'expandIcon' => 'fa fa-angle-right',
'levels' => 1,
'selectedBackColor' => '#fff',
'selectedColor' => '#2eaadc',
],
]); ?>