Can anyone help me? I have created a table with checkbox. but I keep losing the table header name because it was being replaced by the checkbox. The first column with checkbox should be Notify Me and the other is Email Me. How can I put those header names together with the checkbox? here is the code that I have created:
<template>
<Modal #close="doClose">
<template v-slot:container>
<section class="card settings-vue-modal-container">
<header class="card-header">
<h2>Settings</h2>
<!-- <span class="custom-close fa fa-times" #click="doClose"></span> -->
</header>
<div class="card-body">
<div class='table-design'>
<SimpleDatatable
:init_data="tableData"
:init_columns="columns"
:init_is_loading="isTableLoading"
:isColumnCustomizable="false"
:isBoredered="true"
:isTableHeaderSticky="true"
:removeBorderWrapper="true"
:showTotalResult="false"
tableContentClass="users-table-content"
#changePage="changePage"
#getTableData="setTableData"
#getSelectedData="getSelectedData"
>
</SimpleDatatable>
</div>
</div>
<footer class="card-footer">
<div class="btn-group ml-auto float-right">
<button type="button" class="btn btn-secondary btn-close" #click="doClose">Close</button>
</div>
</footer>
</section>
</template>
</Modal>
</template>
<script>
import Modal from "../Reusable/Modal"
import SimpleDatatable from '../Others/SimpleDatatable';
export default {
components: {
Modal,
SimpleDatatable
},
data() {
return {
settingsData: [],
isTableLoading: false,
params: {
page: this.currentPage,
page_limit: 10,
search: '',
role: ''
},
columns: [
{
label: 'Task Schedule',
field: 'name',
align: 'center',
default: true
},
{
label: 'Notify Me',
type: 'checkbox',
align: 'center',
width: 200
},
{
label: 'Email Me',
type: 'checkbox',
align: 'center',
width: 200
}
],
tableData: {},
currentPage: 1,
selectedData: [],
requiredData: {},
errors: {},
name: '',
};
},
created() {
this.getTableData()
},
watch: {
currentPage(newValue, oldValue) {
this.params.page = newValue
this.getTableData()
}
},
methods: {
doClose() {
this.errors = {};
this.name = '';
this.$emit('close');
},
changePage(event) {
this.currentPage = event
},
setTableData(data) {
this.tableData = data
},
getSelectedData(data) {
this.selectedData = data.map(x => x.id)
},
getTableData() {
this.isTableLoading = true
let url = '/tasks/api/getAll'
axios
.post(url, this.params)
.then(response => {
this.setTableData(response.data)
this.isTableLoading = false
})
.catch(errors => {
this.isTableLoading = false
console.log(errors)
})
},
}
}
</script>
Thank you. Below is also the SimpleDatatable being used:
<template>
<div class="row">
<SeeMore
:content="this.seeMoreContent"
v-show="seeMoreModalVisibility"
#close="seeMoreModalVisibility=false"
/>
<div class="col-lg-12">
<CustomizeColumnModal
v-show="showColumnModal"
#close="showColumnModal = false"
:columns="init_columns"
#getCols="getColumn"
/>
</div>
<div class="col-lg-12">
<div
class="panel panel-default"
style="margin-bottom: 0"
:class="{ 'no-border': removeBorderWrapper }"
>
<div
class="panel-body"
style="margin-bottom: 0"
:class="{ 'no-border': removeBorderWrapper }"
>
<loading :active.sync="isLoading" :is-full-page="fullPage" style="z-index: 3;"></loading>
<div class="pull-left">
<slot name="functional_upper_left"></slot>
<b
class="ml-3"
v-if="data.total && showTotalResult && totalResultPosition === 'upperLeft' "
>Total Result: {{data.total | addComma }}</b>
</div>
<button
class="btn btn-lg btn-primary pull-right"
v-if="isColumnCustomizable"
#click="showColumnModal = true"
style="margin-bottom: 15px;"
>
<span class="fa fa-list" style=" margin-right: 5px;"></span> Columns
</button>
<slot name="functional_buttons"></slot>
<div class="table table-responsive" style="overflow: auto; max-height: 550px;">
<table
class="table table-hover table-striped"
:class="{ 'table-bordered': isBoredered }"
style="margin-bottom: 0"
>
<thead>
<tr>
<th
v-for="(col, index) in columns"
:class="{'amzentrix-th-sticky' : isTableHeaderSticky, 'with-select-dropdown': col.type === 'checkbox' && isSelectOptions }"
:key="index"
:style="{ minWidth: (col.width) ? `${col.width}px`: '100px', textAlign: (col.align) ? `${col.align}` : 'left' }"
>
<template v-if="col.type === 'checkbox'">
<div class="dropdown">
<input type="checkbox" #click="doSelectAll" v-model="isSelectAll" />
<a
class="dropdown-toggle"
id="dropdownSelectOptions"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
v-if="isSelectOptions"
/>
<div class="dropdown-menu" aria-labelledby="dropdownSelectOptions">
<span class="dropdown-item" #click="doSelectAllOnly">Select All</span>
<span class="dropdown-item" #click="doSelectTop(10)">Select Top 10</span>
<span class="dropdown-item" #click="doSelectTop(20)">Select Top 20</span>
</div>
</div>
</template>
<template v-else-if="col.sortable">
<div class="sortable_col" #click="sortCol(index)">
<span>{{ col.label }}</span>
<span class="sortable_icons">
<i class="fa fa-sort-up" :class="{ active: col.currentSort === 'ASC'}" />
<i
class="fa fa-sort-down"
:class="{ active: col.currentSort === 'DESC'}"
/>
</span>
</div>
</template>
<template v-else>{{ col.label }}</template>
</th>
</tr>
</thead>
<tbody v-if="data.total !== 0">
<template v-for="(row, index) in data.data">
<tr :key="index">
<td
v-for="(col, index) in columns"
:class="tableContentClass"
:style="{
textAlign: (col.align) ? `${col.align}` : 'left',
'vertical-align': (col.valign) ? col.valign : 'middle'
}"
:key="index"
>
<template v-if="col.type == 'checkbox' ">
<div class="vue-checkbox">
<input
type="checkbox"
:checked="row.selected"
#click="doSelect(row, $event)"
/>
</div>
</template>
<template v-else-if="col.type === 'action'">
<slot :name="`action-${row.id}`">
<slot name="action" :data="row" />
</slot>
</template>
<template v-else-if="col.type == 'date'">{{ timeHumanize(row[col.field]) }}</template>
<template
v-else-if="col.type == 'complete_date'"
>{{ completeDateFormat(row[col.field]) }}</template>
<template v-else-if="col.type == 'raw'">
<div v-html="row[col.field]"></div>
</template>
<template v-else-if="col.type == 'rounded_numbers'">
<div>{{ row[col.field] ? Number(row[col.field]).toFixed(4) : row[col.field] }}</div>
</template>
<template
v-else-if="col.type == 'status'"
>{{ row[col.field] ? 'Active': 'Inactive' }}</template>
<template v-else-if="col.type == 'more'">
<div v-if="row[col.field]">
<p v-html="seeMoreTexts(row[col.field].replace(/<\/?[^>]+(>|$)/g, ''))"></p>
<small
class="see-more"
#click="seeMore(row[col.field])"
v-if="row[col.field].length> 20"
>See More</small>
</div>
<p v-else>-</p>
<!-- {{ row[col.field] ? '<h1>awit</h1>' : '-' }} -->
</template>
<template v-else-if="col.type == 'field_value'">
<slot name="field_value" :data="row"></slot>
</template>
<template v-else>{{ row[col.field] ? row[col.field] : '-' }}</template>
</td>
</tr>
</template>
</tbody>
<tbody v-else>
<tr>
<td align="center" colspan="1000">
<slot name="no-result">
<span style="margin-right: 5px">No Data Found.</span>
</slot>
</td>
</tr>
</tbody>
</table>
</div>
<!-- PAGINATION -->
<nav v-if="data.total && data.total !== 0 && !data.single">
<ul class="pagination" :class="`float-${paginationPosition}`">
<li
class="page-item pagination-total-result px-3"
v-if="data.total && showTotalResult && totalResultPosition === 'bottomPaginationLeftSide'"
>
Total Result:
<b class="ml-2">{{data.total | addComma }}</b>
</li>
<slot name="pagination-left" />
<li class="page-item pr-3 page-limit-select" v-if="isCustomResultPerPage">
<label for="results-per-page">Results per page:</label>
<input
class="form-control"
id="results-per-page"
type="number"
min="1"
#change="handleChangeItemsPerPage"
v-model="page_limit"
/>
</li>
<li
class="page-item"
:class=" data.current_page <= 1 ? 'disabled' : '' "
#click=" changePage((data.current_page - 1))"
>
<a
class="page-link"
:href=" (data.current_page > 1) ? `#page-${data.current_page - 1}` : `#page-1`"
aria-label="Previous"
>
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li>
<li
class="page-item"
v-for="(n, index) in pagination(data.current_page, data.last_page)"
:class="(n === data.current_page) ? 'active' : ''"
:key="index"
#click="changePage(n)"
>
<a class="page-link" :href="(typeof n == 'number') ? `#page-${n}` : '#' ">{{ n }}</a>
</li>
<li
class="page-item"
:class=" data.current_page >= data.last_page ? 'disabled' : '' "
#click=" changePage((data.current_page + 1))"
>
<a
class="page-link"
:href=" (data.current_page < data.last_page) ? `#page-${data.current_page + 1}` : `#page-${data.last_page}`"
aria-label="Next"
>
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li>
<slot name="pagination-right" />
</ul>
</nav>
</div>
</div>
</div>
</div>
</template>
<style scoped src='bootstrap/dist/css/bootstrap.min.css'></style>
<script>
import moment from "moment";
import CustomizeColumnModal from "./Datatable/CustomizeColumn";
import SeeMore from "./SimpleDatatableModal";
export default {
components: {
CustomizeColumnModal,
SeeMore
},
props: {
init_data: {
type: Object,
required: true
},
init_columns: {
type: Array,
required: true
},
init_is_loading: {
type: Boolean,
default: false
},
init_page_limit: {
type: Number,
default: 0
},
isSelectOptions: {
type: Boolean,
default: false
},
isColumnCustomizable: {
type: Boolean,
default: false
},
isBoredered: {
type: Boolean,
default: false
},
isTableHeaderSticky: {
type: Boolean,
default: false
},
isCustomResultPerPage: {
type: Boolean,
default: false
},
removeBorderWrapper: {
type: Boolean,
default: false
},
showTotalResult: {
type: Boolean,
default: false
},
totalResultPosition: {
type: String,
default: "upperLeft"
},
tableContentClass: {
type: String,
default: ""
},
paginationPosition: {
type: String,
default: "left"
}
},
data() {
return {
data: { total: 0 },
columns: this.init_columns,
isLoading: this.init_is_loading,
fullPage: false,
isSelectAll: false,
showColumnModal: false,
seeMoreContent: "",
seeMoreModalVisibility: false,
page_limit: this.init_page_limit
};
},
watch: {
init_data(newData, oldData) {
this.data = newData;
this.isSelectAll = false;
if (this.isSelectOptions) {
this.getSelectedData();
}
},
init_is_loading(newData, oldData) {
this.isLoading = newData;
if (this.isSelectOptions) {
this.checkSelectHeaderModel(); //Will reset isSelectAll State. Important if you're using checkbox and with dynamic data.
}
},
init_columns(newCols) {
this.columns = newCols;
},
init_page_limit(newData) {
this.page_limit = newData;
}
},
filters: {
addComma(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
},
methods: {
resetSortColFields() {
const withSortColFields = this.columns.filter(col => col.currentSort);
const resetColFields = withSortColFields.map(col => {
col.currentSort = null;
return col;
});
},
//returns an object with sortType (eg. ASC or DESC ) and field (eg. DATE, ID)
sortCol(index) {
const { currentSort } = this.columns[index];
let sort = null;
this.resetSortColFields();
switch (currentSort) {
case "ASC":
sort = null;
break;
case "DESC":
sort = "ASC";
break;
default:
sort = "DESC";
}
this.columns[index].currentSort = sort;
this.$emit("sort", {
sortType: sort,
field: sort ? this.columns[index].field : null
});
},
doSelectAll(event) {
//single property for single set of data, means no paginated data.
//usually you want to use this if you're not using primarily the api of laravel's pagination.
//you just need to pass an initial object data with data and single properties
if (!this.data.total && !this.data.single) {
event.preventDefault();
return;
}
this.isSelectAll = !this.isSelectAll;
this.data.data.forEach(element => {
element.selected = this.isSelectAll;
});
if (!this.isSelectAll) this.$emit("getDeselectedData", this.data.data);
this.$emit("getTableData", this.data);
this.getSelectedData();
},
doSelectAllOnly() {
if (!this.isSelectAll) this.doSelectAll();
},
doSelectTop(num) {
this.data.data.forEach((element, index) => {
if (num > index) element.selected = true;
});
this.getSelectedData();
},
checkSelectHeaderModel() {
// to check if all data from the data is selected, if true, checkbox from header must be checked.
if (!this.data.data) return;
const newDataLength = this.data.data.length;
const newSelectedDataLength = this.data.data.filter(data => data.selected)
.length;
this.isSelectAll =
newDataLength && newDataLength === newSelectedDataLength ? true : false;
},
doSelect(row, event) {
let checked = Boolean(row.selected);
row.selected = !checked;
if (!row.selected) {
this.$emit("getDeselectedItem", row);
}
this.getSelectedData();
},
getSelectedData() {
const selected = this.data.data.filter(el => el.selected);
this.checkSelectHeaderModel();
this.$emit("getSelectedData", selected);
},
getColumn(event) {
if (this.isColumnCustomizable) {
this.columns = event;
this.$emit("getSelectedColumns", event);
}
},
timeHumanize(date) {
return moment(date).isValid() ? moment(date).fromNow() : date;
},
completeDateFormat(date) {
return moment(date).isValid()
? moment(date).format("MMM Do YYYY h:mm:ss a")
: date;
},
changePage(pageNumber) {
this.handleChangeItemsPerPage();
if (
pageNumber > 0 &&
pageNumber <= this.data.last_page &&
typeof pageNumber == "number" &&
this.data.current_page != pageNumber
)
this.$emit("changePage", pageNumber);
},
pagination(c, m) {
let current = c,
last = m,
delta = 3,
left = current - delta,
right = current + delta + 1,
range = [],
rangeWithDots = [],
l;
for (let i = 1; i <= last; i++) {
if (i == 1 || i == last || (i >= left && i < right)) {
range.push(i);
}
}
for (let i of range) {
if (l) {
if (i - l === 2) {
rangeWithDots.push(l + 1);
} else if (i - l !== 1) {
rangeWithDots.push("...");
}
}
rangeWithDots.push(i);
l = i;
}
return rangeWithDots;
},
seeMoreTexts(text) {
return text.length > 20 ? text.substring(0, 40) + "..." : text;
},
seeMore(data) {
this.seeMoreContent = data;
this.seeMoreModalVisibility = true;
},
handleChangeItemsPerPage(event) {
let value;
let changePage = false;
if (typeof event == "object") {
value = parseInt(event.target.value);
changePage = true;
} else {
value = parseInt(this.page_limit);
}
if (value <= 0 || typeof value != "number" || !value) {
value = 10;
this.page_limit = 10;
}
this.$emit("handleChangeItemsPerPage", parseInt(value), changePage);
}
},
mounted() {
//single property for single set of data, means no paginated data.
//usually you want to use this if you're not using primarily the api of laravel's pagination.
//you just need to pass an initial object data with data and single properties
this.data =
this.init_data.total || this.init_data.single
? this.init_data
: { total: 0 };
}
};
</script>
Related
I have a form in reactjs which has a normal variable called "name" and two arrays, one called "data1" and the other "data2", but when saving from reactjs it is only saving the variable "name" in base of data.
I need that they also save the arrangements in the database but I have not achieved it.
the mysql database only has one table called revenue2 and 4 fields: revenue_id, name, data1, data2
https://codesandbox.io/s/ecstatic-browser-nvcee?file=/src/App.js
import React, {useState} from 'react';
import axios from 'axios';
import {
Grid,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper
} from "#material-ui/core";
import AddCircleOutlineIcon from "#material-ui/icons/AddCircleOutline";
import { withStyles, makeStyles } from "#material-ui/core/styles";
import DeleteIcon from "#material-ui/icons/Delete";
const StyledTableRow = withStyles((theme) => ({
root: {
"&:nth-of-type(odd)": {
backgroundColor: theme.palette.action.hover
}
}
}))(TableRow);
const options = [
{ value: 1, label: 1 },
{ value: 2, label: 2 },
{ value: 3, label: 3 }
];
function Pruebas() {
const baseUrlAd = 'https://www.inventarios.gemcont.com/apiGemcont/compras/ingresos/';
const [data, setData]=useState([]);
const [frameworkSeleccionado, setFrameworkSeleccionado]=useState({
id_ingreso:'',
nombre:'',
dato1:'',
dato2:''
});
const handleChange=e=>{
const {name, value}=e.target;
setFrameworkSeleccionado((prevState)=>({
...prevState,
[name]: value
}))
console.log(frameworkSeleccionado);
}
const peticionPost = async() =>{
var f = new FormData();
f.append("nombre", frameworkSeleccionado.nombre);
f.append("dato1", frameworkSeleccionado.dato1);
f.append("dato2", frameworkSeleccionado.dato2);
f.append("METHOD", "POST_prueba");
await axios.post(baseUrlAd,f)
.then(response=>{
setData(data.concat(response.data));
}).catch(error=>{
console.log(error);
})
}
const [roomInputs, setRoomInputs] = useState([
{ dato1: "", dato2: "" }
]);
const handleRoomChange = (value, index, name) => {
const list = [...roomInputs ];
list[index][name] = value;
setRoomInputs(list);
};
const handleRemoveClickRoom = (index) => {
const list = [...roomInputs];
list.splice(index, 1);
setRoomInputs(list);
};
const handleAddClickRoom = () => {
setRoomInputs([...roomInputs, { dato1: "", dato2: "" }]);
};
return (
<div className="content-wrapper">
<div className="content-header">
<div className="container-fluid">
<div className="col-sm-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Datos</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4">
<div class="input-group">
<input type="text" name="nombre"
placeholder='nombre' className="form-control" onChange={handleChange}/>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<br />
<Grid item sm={12}>
<TableContainer component={Paper} variant="outlined">
<Table aria-label="customized table">
<TableHead>
<TableRow>
<TableCell>#</TableCell>
<TableCell align="left">dato1</TableCell>
<TableCell align="left">dato2</TableCell>
</TableRow>
</TableHead>
<TableBody>
{roomInputs.map((x, i) => (
<StyledTableRow key={i}>
<TableCell component="th" scope="row">
{i + 1}
</TableCell>
<TableCell align="left">
<input
type="text"
className="form-control"
name="dato1"
value={options.value}
//onChange={option => handleRoomChange(option, i, "dato1")}
onChange={event => handleRoomChange(event.target.value, i, "dato1")}
/>
</TableCell>
<TableCell align="left">
<input
type="number"
name="dato2"
className="form-control"
value={options.value}
//onChange={option => handleRoomChange(option, i, "dato2")}
onChange={event => handleRoomChange(event.target.value, i, "dato2")}
/>
</TableCell>
<TableCell align="left">
{roomInputs.length !== 1 && (
<DeleteIcon
onClick={() => handleRemoveClickRoom(i)}
style={{
marginRight: "10px",
marginTop: "4px",
cursor: "pointer"
}}
/>
)}
{roomInputs.length - 1 === i && (
<AddCircleOutlineIcon
onClick={handleAddClickRoom}
style={{ marginTop: "4px", cursor: "pointer" }}
/>
)}
</TableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Grid>
</div>
</div>
<br />
<button className="btn btn-primary" onClick={()=>peticionPost()}> Registrar</button>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Pruebas
php
<?php
include '../../bd/global.php';
header('Access-Control-Allow-Origin: *');
if($_POST['METHOD']=='POST_prueba'){
unset($_POST['METHOD']);
$nombre=$_POST['nombre'];
$dato1=$_POST['dato1'];
$dato2=$_POST['dato2'];
$query="insert into ingresos2(nombre,dato1,dato2) values ('$nombre','$dato1','$dato2')";
$queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos2";
$resultado=metodoPost($query, $queryAutoIncrement);
echo json_encode($resultado);
header("HTTP/1.1 200 OK");
exit();
}
header("HTTP/1.1 400 Bad Request");
?>
Refactor handleChangeRoom as below
const handleRoomChange = (value, index, name) => {
setFrameworkSeleccionado((prevState) => ({
...prevState,
[name]: value
}));
};
Demo - https://codesandbox.io/s/happy-sara-or05xx?file=/src/App.js:2167-2326
I am working on making a mega menu with categories responsive. The site is using Laravel, PHP and a bootstrap framework. I did not write the original code, but as I have made the menu responsive, I have come into an issue.
When I click on the hamburger, it opens the menu. When I click on any internal link, or anywhere on the entire screen, the menu closes. I have tried the "stop propagation on numerous elements with no success. Since this is a custom build where the categories are also used on internal searches, I am not sure how to fix. I did remove the entire menu and put in a static one and everything seemed to work well.
<div class="navbar-buttons">
<div class="login">
Vendor
Sign Up
Log In
</div>
</div>
#else
<div class="navbar-dropdown">
<div class="dropdown">
<button class="btn account-options dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false" style="color: #240462 !important">
<img
src="{{ Auth::user()->provider ? asset('images/avatar/' . Auth::user()->avatar) : asset('storage/' . Auth::user()->avatar) }}"
alt="" style="width: 24px; height: 24px">
{{ Auth::user()->first_name }}
</button>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
#if (Auth::user()->role->name == 'owner' || Auth::user()->role->name == 'author')
<a class="dropdown-item" href="{{ route('vendor-dashboard') }}"><i class="fas fa-briefcase"></i> My
Business</a>
#elseif (Auth::user()->role->name == 'superadmin' || Auth::user()->role->name == 'admin')
<a class="dropdown-item" href="{{ route('admin-dashboard') }}"><i class="fas fa-cog"></i> Admin
Dashboard</a>
#endif
<a class="dropdown-item" href="#"><i class="fas fa-user"></i> My Profile</a>
<a class="dropdown-item" href="#"><i class="fas fa-star"></i> My Reviews</a>
<a class="dropdown-item" href="{{ route('search-favorites') }}?mapView=1"><i class="fas fa-heart"></i> My
Favorites</a>
<a class="dropdown-item logout" href="#"><i class="fas fa-sign-out"></i> Logout</a>
<form name="logoutForm" action="/logout" method="POST">{{ csrf_field() }}</form>
</div>
</div>
</div>
#endif
</div>
</nav>
<a href="" class="ic menu category-dropdown-menu ">
<span class="line"></span>
<span class="line"></span>
<span class="line"></span>
</a>
<div class="category-nav container-fluid">
<div class="container position-relative">
#foreach (\App\PrimaryCategory::orderBy('name')->get() as $primary)
<div class="category-dropdown" data-id="{{ $primary->id }}">
<div class="category-dropdown-title">{{ $primary->name }}</div>
</div>
<div class="category-dropdown-menu" data-id="{{ $primary->id }}">
<div class="row">
<?php $last = 0; $cols = 1; ?>
<div class="col-3">
#foreach ($primary->secondary_categories->sortBy('name')->sortBy('menu_sequence') as $secondary)
<?php
if ($secondary->menu_display_tertiaries)
$cur = 3 + count($secondary->tertiary_categories);
else
$cur = 3;
?>
#if ($last + $cur > 26)
<?php $last = 0; $cols++ ?>
</div>
<div class="col-3">
#endif
<div class="category-secondary">
<div class="category-secondary-title">
<a href="/listings?pc={{ $primary->id }}&sc={{ $secondary->id }}">{{ $secondary->name }}
»</a>
#if ($secondary->menu_display_tertiaries)
<hr>
#endif
</div>
#if ($secondary->menu_display_tertiaries)
<div class="category-secondary-menu">
#foreach ($secondary->tertiary_categories->sortBy('name')->sortBy('menu_sequence') as
$tertiary)
#if ($tertiary->menu_display)
{{ $tertiary->name }}<br>
#endif
#endforeach
</div>
#endif
</div>
<?php $last += $cur ?>
#endforeach
</div>
#for ($i = 0; $i < (3 - $cols); $i++) <div class="col-3">
</div>
#endfor
<div class="dropdown-image">
<img src="{{ asset('/images/category/category2.png') }}" alt="">
</div>
</div>
</div>
#endforeach
#if (!Auth::guest())
#if (!isset($favorites))
<div class="search-favorites">
<i class="fas fa-heart"></i>
</div>
#else
<div class="undo-favorites">
<i class="fas fa-minus-circle"></i>
</div>
#endif
#else
<div class="search-favorites favorites-guest" data-toggle="modal" data-target="#favorites-modal">
<i class="fas fa-heart"></i>
</div>
#endif
</div>
</div>
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script src="{{ asset('js/bootstrap.js') }}"></script>
<script>
$('input[name="q"]').focus(function () {
$(this).parent().find('.input-group-prepend').addClass('d-none');
$(this).css('border-left', '1px solid #ced4da');
$(this).css('border-top-left-radius', '.25rem');
$(this).css('border-bottom-left-radius', '.25rem');
$(this).css('padding-left', '10px');
});
$('input[name="q"]').focusout(function () {
if ($(this).val() == '') {
$(this).parent().find('.input-group-prepend').removeClass('d-none');
$(this).css('border-left', 'none');
$(this).css('border-top-left-radius', '0');
$(this).css('border-bottom-left-radius', '0');
$(this).css('padding-left', '0');
}
});
#if(isset($_GET['login-modal']))
$('#login-modal').modal({
backdrop: 'static',
});
#elseif(isset($_GET['register-modal']))
$('#register-modal').modal({
backdrop: 'static',
});
#endif
function session_check(modal) {
var url = "{{ route('session-check') }}";
var options = {
_token: "{{ csrf_token() }}",
};
$.post(url, options).done(function (data) {
if (data.substr(0, 1) === '{') {
$('#' + modal).modal({
backdrop: 'static',
});
} else {
var current_url = '{!! Request::fullUrl() !!}';
current_url = current_url.replace('?login-modal=1&', '?');
current_url = current_url.replace('?login-modal=1', '');
current_url = current_url.replace('&login-modal=1', '');
current_url = current_url.replace('?register-modal=1&', '?');
current_url = current_url.replace('?register-modal=1', '');
current_url = current_url.replace('®ister-modal=1', '');
window.location = current_url + (current_url.match(/\?/) ? '&' : '?') + modal + '=1';
}
});
}
$('.login-with-email').click(function () {
$('.first-wrap').addClass('d-none');
$('.second-wrap').removeClass('d-none');
$('.login-back').removeClass('d-none');
});
$('.login-back, .login-link').click(function () {
$('.login-back').addClass('d-none');
$('.first-wrap').removeClass('d-none');
$('.second-wrap').addClass('d-none');
});
$('.logout').click(function () {
$('form[name="logoutForm"]').submit();
});
$('.category-dropdown, .category-dropdown-menu').mouseover(function () {
var id = $(this).data('id');
$('.category-dropdown-menu').each(function () {
if ($(this).data('id') == id)
$(this).removeClass('d-none');
});
$('.category-dropdown').each(function () {
if ($(this).data('id') == id) {
$(this).css('background', '#f0f0f0');
$(this).css('border-left', '1px solid #ccc');
$(this).css('border-right', '1px solid #ccc');
$(this).css('border-bottom', 'none');
$(this).css('padding-bottom', '1px');
}
});
});
$('.category-dropdown-menu').mouseleave(function () {
var id = $(this).data('id');
$('.category-dropdown-menu').each(function () {
if ($(this).data('id') == id)
$(this).addClass('d-none');
});
$('.category-dropdown').each(function () {
if ($(this).data('id') == id) {
$(this).css('background', 'none');
$(this).css('border-left', 'none');
$(this).css('border-right', 'none');
$(this).css('border-bottom', '1px solid #ccc');
$(this).css('padding-bottom', '0');
}
});
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js">
</script>
<script>
$(function () {
$('form[name="loginform"]').validate({
rules: {
email: {
required: true,
maxlength: 255,
email: true,
},
password: {
required: true,
},
},
messages: {
email: {
required: '* You must enter your email address to sign in.',
maxlength: '* This email address is too long [max 255 characters]',
email: '* This is not a valid email address.',
},
password: {
required: '* You must enter your password to sign in.',
},
},
submitHandler: function (form) {
form.submit();
}
});
$('form[name="registerform"]').validate({
rules: {
first_name: {
required: true,
maxlength: 255,
},
last_name: {
required: true,
maxlength: 255,
},
email: {
required: true,
maxlength: 255,
email: true,
remote: {
url: "{{ route('verify-unique-email-no-invites') }}",
type: 'post',
data: {
_token: '{{ csrf_token() }}',
email: function () {
return $('#sign-up-email').val();
}
},
},
},
password: {
required: true,
minlength: 6,
},
password_confirmation: {
required: true,
minlength: 6,
equalTo: '#sign-up-password',
},
},
messages: {
first_name: {
required: '* You must enter your first name to sign up.',
maxlength: '* This email address is too long [max 255 characters]',
},
last_name: {
required: '* You must enter your last name to sign up.',
maxlength: '* This email address is too long [max 255 characters]',
},
email: {
required: '* You must enter your email address to sign up.',
maxlength: '* This email address is too long [max 255 characters]',
email: '* This is not a valid email address.',
remote: '* This email is already in use.',
},
password: {
required: '* You must enter a password to sign up.',
minlength: '* Your password must be 6 characters or longer.',
},
password_confirmation: {
required: '* You must confirm your password to sign up.',
minlength: '* Your password must be 6 characters or longer.',
equalTo: '* Your passwords do not match.',
},
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
},
submitHandler: function (form) {
form.submit();
}
});
$('form[name="loginform"] input').change(function () {
$('form[name="loginform"]').valid();
});
$('form[name="registerform"] input').change(function () {
$('form[name="registerform"]').valid();
});
});
</script>
#yield('scripts')
I'm in the beginning of learning laravel and vue-js, so this is rather difficult to me. I want to make a component in vue-js with a table, with sorting and pagination.
When I started the project I only used Laravel and jquery, so now I'm turning to vue js and it's getting complicated. What I have is this:
In my index.blade.php
#extends('layouts.dashboard')
#section('content')
<div class="container">
<div class="row">
<div class="col">
<table class="table">
<thead>
<tr>
<th> #sortablelink('first_name','First name') </th>
<th> #sortablelink('last_name', 'Last name') </th>
<th> #sortablelink('email', 'E-mail address') </th>
<th> #sortablelink('created_at', 'Creation date') </th>
<th></th>
</tr>
</thead>
<tbody is="submissions"></tbody>
</table>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
{{ $submissions->appends(\Request::except('page'))->render() }}
<div class="total-submissions">
Total submissions:
{{ $submissions->firstItem() }}-{{ $submissions->lastItem() }} of {{ \App\Submission::count() }}
</div>
</div>
</div>
</div>
#stop
In my component Submissions.vue:
<template>
<tbody>
<tr v-for="submission in submissions" :key="submission.id">
<td> {{submission.first_name}}</td>
<td> {{submission.last_name}} </td>
<td> {{submission.email}} </td>
<td> {{submission.created_at}} </td>
<td>
<a class="btn btn-default btn-primary" id="btn-view"
:href="'/dashboard/submissions/' + submission.id">View</a>
<a class="btn btn-default btn-primary"
id="btn-delete"
:href="'/dashboard/submissions'"
#click.prevent="deleteSubmission(submission)">Delete</a>
<label class="switch">
<input class="slider-read" name="is_read"
v-model="submission.is_checked"
#change="updateCheckbox(submission)"
type="checkbox">
<span class="slider round"></span>
</label>
</td>
</tr>
</tbody>
</template>
<script>
import qs from 'qs';
import axios from 'axios';
export default {
data: function () {
return {
submissions: [],
}
},
beforeCreate() {
},
created() {
},
mounted() {
this.fetch();
},
methods: {
fetch: function () {
let loader = this.$loading.show();
var queryString = window.location.search;
if (queryString.charAt(0) === '?')
queryString = queryString.slice(1);
var args = window._.defaults(qs.parse(queryString), {
page: 1,
sort: 'id',
order: 'asc'
});
window.axios.get('/api/submissions?' + qs.stringify(args)).then((response) => {
loader.hide();
this.submissions = response.data.data
});
},
deleteSubmission(submission) {
this.$dialog.confirm("Are you sure you want to delete this record?", {
loader: true
})
.then((dialog) => {
axios.delete('api/submissions/' + submission.id)
.then((res) => {
this.fetch()
})
.catch((err) => console.error(err));
setTimeout(() => {
console.log('Delete action completed');
swal({
title: "Update Completed!",
text: "",
icon: "success",
});
dialog.close();
}, 1000);
})
.catch(() => {
console.log('Delete aborted');
});
},
updateCheckbox(submission)
{
this.$dialog.confirm("Are you sure?", {
loader: true
})
.then((dialog) => {
axios.put('/api/submissions/' + submission.id, submission,
)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
setTimeout(() => {
console.log('Action completed');
dialog.close();
swal({
title: "Update Completed!",
text: "",
icon: "success",
});
}, 0);
})
.catch(() => {
submission.is_checked === false ? submission.is_checked = true : submission.is_checked = false;
console.log('Aborted');
});
},
}
}
</script>
Now what I want to accomplish: Put everything in the component, but since I have php in the table to sort everything how can I do this in vue? I'm trying with bootstrap vue tables, but I'm not sure if I can display data like this. Thanks in advance.
So I had a pretty awesome vuejs app that was working flawlessly however it fails when I put it into a vue component. I keep getting the following error. [Vue warn]: Error compiling template Heres the code for my component that I am including (components.php) :
<script>Vue.component('profileinfo', {
template: `<div id="profileInfo">
<div class="sectionHeader">Profile</div>
<div class="dataPoint">First: {{firstNameBraintree}}</div>
<div class="dataPoint">Last: {{lastNameBraintree}}</div>
<div class="dataPoint">Company: {{companyBraintree}}</div>
<div class="dataPoint">Email: {{emailBraintree}}</div>
<div class="dataPoint">Phone: {{phoneBraintree}}</div>
<div class="buttonDiv">
<input class="button" type="button" value="Update" v-on:click="showUpdateProfileForm()">
</div>
</div>
<!--Show Update Profile Form-->
<div class="updateProfileForm" v-show="showupdateprofileinfoform==true">
<h2>Update Account Information</h2>
<h2>Username: <?php echo $_SESSION['username'];?></h2>
<!--PASSWORD-->
<div class="inputDiv">
<p v-show="passwordLengthMet==true && passwordHasCap==true && passwordHasNum==true || password.length=='' && passwordHasCap==false && passwordHasNum==false">Password * <i class="fa fa-check-circle success"></i> Valid</p>
<p v-show="passwordLengthMet==false && password.length!='' || passwordLengthMet==true && passwordHasCap==false || passwordLengthMet==true && passwordHasNum==false">Password * <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Password must be at least 8 characters, Have a capital letter and contain a number</span></i></p>
<input type="password" v-model="password" placeholder="********" v-on:focus="showpasswordrequirements">
<ul v-show="dispassr==true">
<li v-show="passwordLengthMet==false || password==''">Must contain at least 8 characters</li>
<li v-show="passwordHasCap==false">Must contain capital letter</li>
<li v-show="passwordHasNum==false">Must contain number</li>
</ul>
</div>
<!--END PASSWORD-->
<!--PASSWORDS MATCH-->
<div class="inputDiv">
<p v-show="passwordsMatch==true">Confirm Password* <i class="fa fa-check-circle success"></i> Passwords Match</p>
<p v-show="passwordsMatch==false">Confirm Password* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please make sure passwords match</span></i></p>
<input type="password" v-model="confirmPassword" placeholder="********" v-on:focus="showconfirmpasswordrequirements">
<ul v-show="disconfr==true">
<li class="blue" v-show="passwordsMatch==false || confirmPassword==''">Please be sure your passwords match</li>
</ul>
</div>
<!--END PASSWORDS MATCH-->
<!--FIRSTNAME-->
<div class="inputDiv">
<p v-show="validFirstname==true">First name* <i class="fa fa-check-circle success"></i> Valid</p>
<p v-show="validFirstname==false && sub==1">First Name* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please enter your firstname</span></i></p>
<p v-show='validFirstname==false && sub!="1"'>First Name* <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Please enter a firstname</span></i></p>
<input v-model="firstName" placeholder="Firstname" v-on:focus="showfirstnamerequirements">
<ul v-show='disfnamer==true'>
<li v-show="validFirstname==false">Please enter a firstname</li>
</ul>
</div>
<!--END FISTNAME-->
<!--LASTNAME-->
<div class="inputDiv">
<p v-show="validLastname==true">Last Name* <i class="fa fa-check-circle success"></i> Valid</p>
<p v-show="validLastname==false && sub==1">Last Name* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please enter your lastname</span></i></p>
<p v-show='validLastname==false && sub!="1"'>Last Name* <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Please enter a lastname</span></i></p>
<input v-model="lastName" placeholder="Last name" v-on:focus="showlastnamerequirements">
<ul v-show='dislnamer==true'>
<li v-show="validLastname==false">Please enter a lastname</li>
</ul>
</div>
<!--END LASTNAME-->
<!--EMAIL-->
<div class="inputDiv">
<p v-show="validEmail==true">Email* <i class="fa fa-check-circle success"></i> Valid</p>
<p v-show="validEmail==false && email!=='' || email=='' && sub==1">Email* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please enter a valid email</span></i></p>
<p v-show="email=='' && sub==0">Email* <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Please enter a valid email</span></i></p>
<input v-model="email" placeholder="jchang#example.com" v-on:focus="showemailrequirements">
<ul v-show='disemailr==true'>
<li v-show="validEmail==false">Please enter a valid email</li>
</ul>
</div>
<!--END EMAIL-->
<!--PHONE -->
<div class="inputDiv">
<p v-show="phoneLength==true && phoneHasNum==true && phoneNumber!=''">Phone* <i class="fa fa-check-circle success"></i> Valid</p>
<p v-show="phoneLength==false && phoneNumber!='' || phoneHasNum==false && phoneNumber!='' || phoneNumber=='' && sub==1">Phone* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Phone Number must have at least 10 numbers and have no letters, parenthis or dashes</span></i></p>
<p v-show="phoneNumber=='' && sub==0">Phone* <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Phone Number must have at least 10 numbers and have no letters it cannot contain parenthis or dashes</span></i></p>
<input v-model="phoneNumber" placeholder="Phone Number 1234567890" v-on:focus="showphonenumberrequirements" id="phoneNumber">
<ul v-show="disphoner==true">
<li v-show="phoneLength==false">Phone number must be 10 numbers long</li>
<li v-show="phoneHasNum==false || phoneNumber==''"> Phone number must contain only numbers</li>
</ul>
</div>
<!--END PHONE-->
<!--COMPANY NAME-->
<div class="inputDiv">
<p v-show="validCompanyName==true">Company Name* <i class="fa fa-check-circle success"></i> Valid</p>
<p v-show="validCompanyName==false && companyName!='' || companyName==false && companyName=='' && sub==1">Company Name* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please enter your company name</span></i></p>
<p v-show="companyName=='' && sub==0">Company Name* <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Please enter your company name</span></i></p>
<input v-model="companyName" placeholder="Company Name" v-on:focus="showcompanynamerequirements">
<ul v-show="discompr==true">
<li v-show="validCompanyName==false">Please enter your company name</li>
</ul>
</div>
<!--END COMPANY NAME-->
<div class="inputDiv">
<div class="sliderWrapper">
<div><strong>Subscribe to Email List</strong></div>
<label class="switch">
<input type="checkbox" v-model="subscribe" value="1">
<span class="slider"></span>
</label>
</div>
</div>
<div class="inputButton">
<input v-on:click="updateAccount()" type="button" class="saveProfileButton" value="Update">
</div>
<div class="inputButton">
<input v-on:click="hideUpdateProfileForm()" type="button" class="cancelProfileButton" value="Cancel">
</div>
</div>
<!--End Update Profile Form-->`,
data() {
return {
showSpinner: false,
showupdateprofileinfoform: false,
password: '',
confirmPassword: '',
firstName: '',
lastName: '',
email: '',
sub: '',
subscribe:'',
dispassr: '',
disconfr: '',
disfnamer: '',
dislnamer: '',
disemailr: '',
disphoner: '',
discompr: '',
phoneNumber: '',
companyName: '',
customerId: '<?php echo $customer->id; ?>',
companyBraintree:'<?php echo $customer->company; ?>',
firstNameBraintree:'<?php echo $customer->firstName; ?>',
lastNameBraintree:'<?php echo $customer->lastName; ?>',
phoneBraintree:'<?php echo $customer->phone; ?>',
emailBraintree:'<?php echo $customer->email; ?>',
phone:'',
updated: ''
}
},
computed: {
passwordsMatch: function() {
this.confirmPassword=this.confirmPassword.replace(/\s/g, '');
if(this.password == this.confirmPassword) {
return true;
} else {
return false;
}
},
passwordLengthMet: function() {
this.password=this.password.replace(/\s/g, '');
if(this.password.trim().length >0 && this.password.trim().length >= 8) {
return true;
} else {
return false;
}
},
passwordHasCap: function(){
if(/[A-Z]/.test(this.password)){return true;} else{return false;}
},
passwordHasNum: function(){
if(/[\d]/.test(this.password)){return true;} else{return false;}
},
validEmail: function() {
this.email=this.email.replace(/\s/g, '');
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (!reg.test(this.email)) {
return false;
}
return true;
},
validLastname: function() {
this.lastName=this.lastName.replace(/\s/g, '');
if(this.lastName.trim().length<1){return false;} else {return true;}
},
validFirstname: function() {
this.firstName=this.firstName.replace(/\s/g, '');
if(this.firstName.trim().length<1){return false;} else{return true;}
},
validCompanyName: function(){
if(this.companyName.trim().length<1){return false;} else{return true;}
},
phoneHasNum: function(){
if(isNaN(this.phoneNumber)){return false;} else {return true;}
},
phoneLength: function(){
this.phoneNumber=this.phoneNumber.replace(/[^0-9]+/g, '');
if(this.phoneNumber.trim().length==10){return true;} else{return false;}
}
},
created: function() {
this.subscribe=1;
this.firstName='<?php if(isset($_SESSION['firstname'])){echo $_SESSION['firstname'];}?>';
this.lastName='<?php if(isset($_SESSION['lastname'])){echo $_SESSION['lastname'];}?>';
this.email='<?php if(isset($_SESSION['email'])){echo $_SESSION['email'];}?>';
this.companyName='<?php if(isset($_SESSION['companyname'])){echo $_SESSION['companyname'];}?>';
this.phoneNumber='<?php if(isset($_SESSION['phonenumber'])){echo $_SESSION['phonenumber'];}?>';
},
methods: {
showUpdateProfileForm: function(){
this.showupdateprofileinfoform=true;
},
hideUpdateProfileForm: function(){
this.showupdateprofileinfoform=false;
},
updateAccount: function() {
this.sub=1;
if(this.validFirstname && this.validLastname && this.validEmail && this.passwordsMatch && this.validCompanyName && this.phoneHasNum && this.firstName!='' && this.lastName!='' && this.email!='' && this.phoneNumber!='' && this.companyName!='' && this.passwordLengthMet && this.passwordHasNum && this.passwordHasCap && this.password!='' && this.confirmPassword!='' || this.validFirstname && this.validLastname && this.validEmail && this.passwordsMatch && this.validCompanyName && this.phoneHasNum && this.firstName!='' && this.lastName!='' && this.email!='' && this.phoneNumber!='' && this.companyName!='' && this.password=='' && this.confirmPassword=='') {
var jsonString = JSON.stringify({
firstName: this.firstName,
lastName: this.lastName,
password: this.password,
email: this.email,
phoneNumber: this.phoneNumber,
companyName: this.companyName,
subscribe: this.subscribe
});
$.ajax({
url: 'updateAccountInfoBackend.php',
dataType: 'json',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: jsonString,
error: function(data){
alert('error');
// window.location.href='successfullycreated.php';
},
success: function(data){
console.log(data);
alert('success');
if(data.updated==1){location.reload();}
if(data.updated==0){location.reload();}
}.bind(this)
});
}
},
showpasswordrequirements: function(){
this.sub=0;
this.dispassr=true;
this.disconfr=false;
this.disfnamer=false;
this.dislnamer=false;
this.disemailr=false;
this.disphoner=false;
this.discompr=false;
},
showconfirmpasswordrequirements: function(){
this.sub=0;
this.dispassr=false;
this.disconfr=true;
this.disfnamer=false;
this.dislnamer=false;
this.disemailr=false;
this.disphoner=false;
this.discompr=false;
},
showfirstnamerequirements: function(){
this.sub=0;
this.dispassr=false;
this.disconfr=false;
this.disfnamer=true;
this.dislnamer=false;
this.disemailr=false;
this.disphoner=false;
this.discompr=false;
},
showlastnamerequirements: function(){
this.sub=0;
this.dispassr=false;
this.disconfr=false;
this.disfnamer=false;
this.dislnamer=true;
this.disemailr=false;
this.disphoner=false;
this.discompr=false;
},
showemailrequirements: function(){
this.sub=0;
this.dispassr=false;
this.disconfr=false;
this.disfnamer=false;
this.dislnamer=false;
this.disemailr=true;
this.disphoner=false;
this.discompr=false;
},
showphonenumberrequirements: function(){
this.sub=0;
this.disphoner=true;
this.dispassr=false;
this.disconfr=false;
this.disfnamer=false;
this.dislnamer=false;
this.disemailr=false;
this.discompr=false;
},
showcompanynamerequirements: function(){
this.sub=0;
this.disphoner=false;
this.dispassr=false;
this.disconfr=false;
this.disfnamer=false;
this.dislnamer=false;
this.disemailr=false;
this.discompr=true;
}
}
});
Heres the code for the vue app itself:
<?php session_start(); ob_start(); unset($_SESSION['accountupdated']); unset($_SESSION['inserteddisplay']); unset($_SESSION['updateddisplay']); unset($_SESSION['creditcardupdated']);
if(isset($_SESSION['didnotdelete']) && $_SESSION['didnotdelete']==1){header('location:unabletodelete.php');}
if(isset($_SESSION['accessdenied']) && $_SESSION['accessdenied']==1){header('location:logout.php');}
if(isset($_SESSION['accountupdated']) && $_SESSION['accountupdated']==0){header('Location:updateaccountinfoerror.php');}
if(isset($_SESSION['kill']) && $_SESSION['kill']==1){header('Location:updateaccountinfoerror.php');}
if(isset($_SESSION['creditcardnotupdated']) && $_SESSION['creditcardnotupdated']==1){header('Location:errorupdatingcreditcard.php');}
if(isset($_SESSION['didnotinsertdisplay']) && $_SESSION['didnotinsertdisplay']==1){header('Location:errorinsertingdisplay.php');}
if(isset($_SESSION['displaynotauthorized']) and $_SESSION['displaynotauthorized']=1){header('Location:notautorizedtoupdatedisplay.php');}
if(isset($_SESSION['didnotupdatedisplay']) && $_SESSION['didnotupdatedisplay']==1){header('Location:didnotupdatedisplay.php');}
$validyear=$_SESSION['validyear'];
$currentmonthyear=$_SESSION['currentmonthyear'];
date_default_timezone_set('America/Denver');
$id = htmlspecialchars($_GET["id"]);
//if(isset($_GET['id']) and $_GET['id']!=$_SESSION['braintreeid']){header('Location:logout.php');}
if(!isset($_SESSION['username'])){header('Location:logout.php');}
require_once 'lib/Braintree.php';
require_once('head.php');
require_once('header.php');
$gateway = new Braintree_Gateway([
'environment' => 'sandbox',
'merchantId' => 'key',
'publicKey' => 'key',
'privateKey' => 'key'
]);
$customer = $gateway->customer()->find($id);
$plans = $gateway->plan()->all();
$plansArray = array();
foreach ($plans as $plan) {
array_push($plansArray, $plan);
}
$subscriptions = array();
foreach ($customer->creditCards as $card) {
foreach ($card->subscriptions as $subscription) {
array_push($subscriptions, $subscription);
}
}
?>
<!doctype html>
<html>
<head>
<title>Get Customers</title>
<link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
<script src="vue.js"></script>
<script src="jquery-3.3.1.js"></script>
<?php require_once('components.php');?>
</head>
<body>
<div id="app">
<div class="profile-containter">
<profileinfo></profileinfo>
</div>
</div>
<!--End Update Display Form -->
<script>
var app = new Vue({
el: '#app',
data: {
},
methods: {
}
});
</script>
<?php include('foot.php');?>
</body>
</html>
Again the strange thing about all this is that it works perfectly if I just leave it in a vue app yet it does not work all of the sudden when I place it in a Vuejs component. I find this very, very strange as it is essentially the same code. If any of you genius coders have any suggestions I would appreciate it. Thank you so so much.
As #Max Sinev mentionned, your template does not have a single root element, which is not possible (see the official documentation).
In order to fix that, you only need to wrap all your html code in a single div like so:
<div>
<div id="profileInfo">
...
<div class="inputButton">
<input v-on:click="hideUpdateProfileForm()" type="button" class="cancelProfileButton" value="Cancel">
</div>
</div>
</div>
I have a project in which i want to retrieve value from database via checkbox. But i cannot do this.
My controller code is
public function browseProfessionals() {
$userRoles = UserRole::whereIn('role_id', [2,3])->get();
$users = array();
$showUsers = array();
foreach ($userRoles as $userRole) {
$users[] = User::find($userRole->user_id);
}
$valid_providers = array();
$all_providers = array();
$user_role_all_providers = UserRole::where('role_id', 2)->get();
foreach ($user_role_all_providers as $user_role_all_provider) {
$all_providers[] = User::where('id', $user_role_all_provider->user_id)->first();
}
foreach ($all_providers as $all_provider) {
$user = User::where('id', $all_provider->id)->first();
$user_detail = UserDetail::where('user_id', $all_provider->id)->first();
$user_meeting = UserMeeting::where('user_id', $all_provider->id)->first();
$user_time = UserTime::where('user_id', $all_provider->id)->first();
if (!empty($user_detail->avatar) && !empty($user_meeting->meeting_id) && !empty($user_time->hour_rate) && $user->is_active == 1 && $user->is_deleted == 0) {
$valid_providers[] = $all_provider;
}
}
$data = [
'valid_providers' => $showUsers,
'industries' => Industry::where('is_active', 1)->where('is_deleted', 0)->get(),
'degrees' => UserDegree::where('degree_id', $user->degree_id)->get(),
];
return view('frontends.browse-professionals', $data);
}
My Blade template is
#extends ('frontends.layouts.app')
#section ('main')
<div id="content-block" class="margin-top-140">
<div class="container-fluid block custom-container">
<h3 class="block-title">Browse Professionals</h3>
<div class="block-subtitle"><span>Connect</span> <span>Learn</span> <span>Inspire</span> <span>Thrive</span> </div>
<div class="row">
{{--<form action="" method="post">--}}
<div class="col-md-2 left-feild">
<div class="margin-bottom-30">
<h3>Search Filters</h3>
</div>
#if(Auth::check() && Auth::user()->user_role->role_id == 1000000)
<div class="be-vidget">
<h3 class="letf-menu-article"> Looking To </h3>
<div class="creative_filds_block">
<div class="radio">
<label><input type="radio" name="lookingTo" onclick="lookingTo(2)"> Seek Advice</label>
</div>
<div class="radio">
<label><input type="radio" name="lookingTo" onclick="lookingTo(3)"> Share Advice</label>
</div>
</div>
</div>
<script>
function lookingTo(e) {
$.ajax({
type: 'POST',
url: '{{ URL::to('looking/to') }}/' + e,
success: function (result) {
$('#browse_professionals').html(result);
}
});
}
</script>
#endif
<div class="be-vidget">
<h3 class="letf-menu-article">Professionals</h3>
<div class="-creative_filds_block">
<div class="fp-panel-wrap">
<a class="toggle-btn active" onclick="open_industry()" href="#" data-target="#ul_industry" id="a_industry">Industry</a>
<ul id="ul_industry" class="fp-panel open" style="overflow:scroll; height:200px;">
#if(!empty($industries))
#foreach($industries as $industry)
<li value="{{ $industry->id }}">{{ (!empty($industry['name'])) ? $industry['name'] : '' }} </li>
#endforeach
#endif
</ul>
<script>
function industry_search(e) {
$.ajax({
type: 'POST',
url: '{{ URL::to('professionals/industry') }}/' + e,
success: function (result) {
$('#education_experience').html(result);
$('#a_industry').attr('class', 'toggle-btn');
$('#ul_industry').css('display', 'none');
$('#education_experience').css('display', 'block');
$('#eduLevel').css('display', 'block');
$('#areaExperience').css('display', 'block');
}
});
}
function open_industry() {
$('#education_experience').css('display', 'block'); // display none hobe na. collapse hoye jabe
// $('#a_industry').attr('class', 'toggle-btn active');
// $('#ul_industry').css('display', 'block');
$('#education_experience').css('display', 'block');
$('#eduLevel').css('display', 'none');
$('#areaExperience').css('display', 'none');
}
</script>
<div id="education_experience" style="">
<a id="a_education" class="toggle-btn" href="#" data-target="#eduLevel">Education Level</a>
<ul id="eduLevel" class="no-link fp-panel" style="overflow:scroll; height:200px;">
#if(!empty($degrees))
#foreach($degrees as $degree)
<li value="{{ $degree->id }}">{{ (!empty($degree['name'])) ? $degree['name'] : '' }}</a> </li>
#endforeach
#endif
</ul>
<a id="a_experience" class="toggle-btn" href="#" data-target="#areaExperience">Areas of Experience</a>
<ul id="areaExperience" class="no-link fp-panel" style="overflow:scroll; height:200px;">
</ul>
</div>
</div>
</div>
</div>
<div class="be-vidget">
<h3 class="letf-menu-article">Meeting Preferences</h3>
<label>Price</label>
<br> <br>
<input type="hidden" id="price_ranger" class="range-slider" value="23"/>
<label style="margin-top: 30px;">Type</label>
<div class="form-group">
<select class="form-input" id="meeting_type">
<option value="3">All</option>
<option value="1">Phone Meeting</option>
<option value="2">Web Meeting</option>
</select>
</div>
</div>
<button id="search_professionals" type="button" class="btn color-2 size-2 btn-block hover-1">Apply Filter</button>
#if(Session::has('remove_filter'))
<button type="button" class="btn btn-danger size-2 btn-block hover-1">Remove Filter</button>
#endif
<script>
var industry = '';
$('#ul_industry li').click(function() {
industry = $(this).attr('value');
});
$("#search_professionals").click(function () {
var degrees = new Array();
$('input[name="degrees_checkbox"]:checked').each(function() {
degrees.push(this.value);
});
var experiences = new Array();
$('input[name="experiences_checkbox"]:checked').each(function() {
experiences.push(this.value);
});
var price_ranger = $("#price_ranger").val();
var price_ranger_array = price_ranger.split(",");
var start_price = price_ranger_array[0];
var end_price = price_ranger_array[1];
var meeting_type = $("#meeting_type").val();
$.ajax({
'type' : 'post',
'url' : '{{ URL::to('search/professionals') }}',
'data' : {
'industry' : industry,
'educationLevels' : degrees,
'areasOfExperiences' : experiences,
'start_price' : start_price,
'end_price' : end_price,
'meeting_type' : meeting_type
},
'success' : function (result) {
console.log(result);
$('#browse_professionals').html(result);
}
});
});
</script>
</div>
{{--</form>--}}
<div class="col-md-10">
<div id="browse_professionals" class="row _post-container_">
#if (!empty($valid_providers))
#foreach ($valid_providers as $provider)
<div class="category-1 custom-column-5">
<div class="be-post">
<figure class="ratio-4-3 be-img-block-alt">
<div class="ratio-inner" style="background-image: url('{{ !empty($provider->user_detail->avatar) ? URL::to($provider->user_detail->avatar) : '' }}')">
<img src="{{ !empty($provider->user_detail->avatar) ? URL::to($provider->user_detail->avatar) : '' }}" alt="{{ !empty($provider->username) ? URL::to($provider->username) : '' }}">
</div>
</figure>
<div class="be-post-title">{{ (!empty($provider->user_share->share)) ? str_limit($provider->user_share->share, 90) : '' }}</div>
<div class="author-post">
<span>{{ !empty($provider->user_detail->first_name) ? $provider->user_detail->first_name : '' }} {{ !empty($provider->user_detail->last_name) ? $provider->user_detail->last_name : '' }}</span>
</div>
<span>{{ (!empty($provider->user_detail->credentials)) ? str_limit($provider->user_detail->credentials, 25) : '' }}</span>
<div data-value="4" class="static-rating"></div>
<div class="info-block clearfix">
<a class="btn color-1 size-2 hover-1 pull-right" href="{{ !empty($provider->username) ? URL::to($provider->username) : '' }}">Contact</a>
<h3 class="rate"> ${{ (!empty($provider->user_time->hour_rate)) ? $provider->user_time->hour_rate : '' }} /hr</h3>
</div>
</div>
</div>
#endforeach
#endif
</div>
</div>
</div>
</div>
</div>
#endsection
My Searchcontroller is
public function searchProfessionals (Request $request)
{
$industry = $request->input('industry');
$educationLevels = $request->input('educationLevels');
$areasOfExperiences = $request->input('areasOfExperiences');
$startPrice = $request->input('start_price');
$endPrice = $request->input('end_price');
$meetingType = $request->input('meeting_type');
if ($meetingType == 1) {
$type = [1, 1];
} elseif ($meetingType == 2) {
$type = [2, 2];
} elseif ($meetingType === 3) {
$type = [1, 2];
} else {
$type = [1, 2];
}
$userMeetings = array();
$userRoles = array();
$users = array();
$showUsers = array();
$userHourRates = array();
// return response($industry);
$userIndus = UserIndustry::where('industry_id', $industry)->get();
if (!empty($userIndus)) {
foreach ($userIndus as $userInd) {
$userHourRates = UserTime::where('user_id', $userInd->user_id)->whereBetween('hour_rate', [$startPrice, $endPrice])->first();
}
// $userHourRates = UserTime::whereBetween('hour_rate', [$startPrice, $endPrice])->get();
if (!empty($userHourRates)) {
foreach ($userHourRates as $userHourRate) {
$userMeetings[] = UserMeeting::whereIn('meeting_id', $type)->where('user_id', $userHourRate->user_id)->first();
}
if (!empty($userMeetings)) {
foreach ($userMeetings as $userMeeting) {
$userRoles[] = UserRole::where('user_id', $userMeeting['user_id'])->where('role_id', '!=', 1)->first();
}
if (!empty($userRoles)) {
foreach ($userRoles as $userRole) {
$users[] = User::find($userRole['user_id']);
}
if (!empty($users)) {
foreach ($users as $u) {
$user = User::find($u['id']);
$userDetail = UserDetail::where('user_id', $u['id'])->first();
$userShare = UserShare::where('user_id', $u['id'])->first();
$userMeeting = UserMeeting::where('user_id', $u['id'])->first();
$userWeek = UserWeek::where('user_id', $u['id'])->first();
$userTime = UserTime::where('user_id', $u['id'])->first();
if (
$user['is_active'] == 1 && $user['is_deleted'] == 0 && !empty($userDetail['avatar']) && !empty($userDetail['first_name']) &&
!empty($userDetail['last_name']) && !empty($userDetail['credentials']) && !empty($userShare['share']) &&
!empty($userShare['seek']) && !empty($userMeeting['meeting_id']) && !empty($userWeek['week_id']) &&
!empty($userTime['start_time']) && !empty($userTime['end_time']) && !empty($userTime['hour_rate'])
) {
$showUsers[] = $u;
}
}
if (!empty($showUsers)) {
$string = '';
foreach ($showUsers as $showUser) {
$userShow = User::find($showUser->id);
$userDetailShow = UserDetail::where('user_id', $showUser->id)->first();
$userShareShow = UserShare::where('user_id', $showUser->id)->first();
$userRatingShow = Review::where('provider_id', $showUser->id)->orWhere('seeker_id', $showUser->id)->avg('rating');
$userTimeShow = UserTime::where('user_id', $showUser->id)->first();
$string .= '
<div class="category-1 custom-column-5">
<div class="be-post">
<figure class="ratio-4-3 be-img-block-alt">
<div class="ratio-inner" style="background-image: url(' . url($userDetailShow->avatar) . ')">
<img src="' . url($userDetailShow->avatar) . '" alt="omg">
</div>
</figure>
<div class="be-post-title">' . str_limit($userShareShow->share, 90) . '</div>
<div class="author-post">
<span>
<a href="' . url($userShow->username) . '">' .
$userDetailShow->first_name . ' ' . $userDetailShow->last_name . '
</a>
</span>
</div>
<span>' . $userDetailShow->credentials . '</span>
</div>
<div data-value="' . $userRatingShow . '" class="static-rating"></div>
<div class="info-block clearfix">
<a class="btn color-1 size-2 hover-1 pull-right" href="' . url($userShow->username) . '">Contact</a>
<h3 class="rate">$' . $userTimeShow->hour_rate . '/hr</h3>
</div>
</div>
</div>
';
}
return response($string);
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
}
Please help me how can i show value via checkbox. Please help me solving this.
Try to debug your JavaScript by F12, and notice there is any error or not.
if not there is no Javascript problem, you can also check ajax request return data on network tab.