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.
Related
I'm starting with Alpine js and I use a component with plus and minus buttons to add or remove items, however this is used in a modal that when invoked brings a specific product, the problem is that when closing the modal and opening it again with another product the component values do not update, is there a way to reset to the initial state?
<div wire:model.defer='{{ $wiremodel }}'
class="input-group input-group-sm {{$size == 'l' ? 'input-group-lg': ''}} {{$size == 's' ? 'input-group-sm': ''}}"
x-data="{ count: {{ $min }}, max:{{ $max }}, min:{{ $min }}, price:{{ $price }},
increment(){
var incre;
if(this.max == 0){
incre = true;
this.count ++;
}else{
this.count == this.max ? incre = false : incre = true;
this.count == this.max ? this.count : this.count++;
}
if(incre){
var oldprice;
var newprice;
oldprice = $('#price_product_button').attr('data-price');
newprice = parseFloat(this.price) + parseFloat(oldprice);
$('#price_product_button').attr('data-price', newprice);
$('#price_product_button').html(newprice.toLocaleString('pt-BR', { style: 'currency' , currency:'BRL'}));
}
},
decrement(){
var decre;
this.count == this.min ? decre = false : decre = true;
this.count == this.min ? this.count : this.count--;
console.log(this.count);
if(decre){
var oldprice;
var newprice;
oldprice = $('#price_product_button').attr('data-price');
newprice = parseFloat(oldprice) - parseFloat(this.price) ;
$('#price_product_button').attr('data-price', newprice);
$('#price_product_button').html(newprice.toLocaleString('pt-BR', { style: 'currency' , currency:'BRL'}));
}
}
}">
<div class="input-group-prepend">
<button #click="decrement() ; $dispatch('input', count)" class="btn btn-outline-light bg-white text-danger" data-price="">
<i class="fas fa-minus"></i>
</button>
</div>
<input readonly x-model.number="count" class="form-control border-0 text-center input-btn-add-remove"
placeholder="{{ $min }}" />
<div class="input-group-append">
<button #click="increment() ; $dispatch('input', count)" class="btn btn-outline-light bg-white text-danger">
<i class="fas fa-plus"></i>
</button>
</div>
</div>```
If the x-data object of a component contains an init() method, it will be called automatically. For example:
<div x-data="{
init() {
this.count = {{ $min }};
this.max = {{ $max }};
this.min = {{ $min }};
this.price = {{ $price }};
}
}">
...
</div>
You can use that fact for your advantage and everytime the modal opens, the init method can be called to reset the values to its original state. Also it will be called automatically on the first init.
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>
I was to Try to save any Invoice Card on Database but it not saved
What's Wrong With my code, I was Try to search to solve this but it not solved
Always Blank to database,
The View Form & Post
The Controller
Use Boostrap 3 from AdminLte Template
<?php
namespace App\Http\Controllers;
use App\Kwitansi;
use Illuminate\Http\Request;
use Haruncpi\LaravelIdGenerator\IdGenerator;
class KwitansiController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$kwitansi = Kwitansi::get();
return view('user.formkwitansi', ['kwitansi' => $kwitansi]);
}
public function store(Request $request)
{
$kwitansi = new Kwitansi;
$id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
$kwitansi->received = $request->received;
$kwitansi->registration = $request->registration;
$kwitansi->course = $request->course;
$kwitansi->trasnportation = $request->trasnportation;
$kwitansi->payment = $request->payment;
$kwitansi->kota = $request->kota;
$kwitansi->register_at = $request->register_at;
$request->validate([
'sum_rp' => 'required',
'sum_text' => 'required',
]);
$sum_rp = $request->registration + $request->course + $request->transportation;
function penyebut($nilai) {
$nilai = abs($nilai);
$huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
$temp = "";
if ($nilai < 12) {
$temp = " ". $huruf[$nilai];
} else if ($nilai <20) {
$temp = penyebut($nilai - 10). " belas";
} else if ($nilai < 100) {
$temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
} else if ($nilai < 200) {
$temp = " seratus" . penyebut($nilai - 100);
} else if ($nilai < 1000) {
$temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
} else if ($nilai < 2000) {
$temp = " seribu" . penyebut($nilai - 1000);
} else if ($nilai < 1000000) {
$temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
} else if ($nilai < 1000000000) {
$temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
} else if ($nilai < 1000000000000) {
$temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
} else if ($nilai < 1000000000000000) {
$temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
}
return $temp;
}
function terbilang($nilai) {
if($nilai<0) {
$hasil = "minus ". trim(penyebut($nilai));
} else {
$hasil = trim(penyebut($nilai));
}
return $hasil;
}
$sum_text = $request->sum_rp;
$kwitansi->sum_rp = $sum_rp;
$kwitansi->sum_text = terbilang($sum_text);
$kwitansi->save();
return redirect('kwitansi')->withSuccess('Added Succesfully');
}
}
The Blade View
Use Form and View in One Page
#extends('layouts.admin')
#section('title', 'Kwitansi')
#section('css')
<!-- DataTables -->
<link rel="stylesheet" href="{{ asset('adminlte/plugins/datatables-bs4/css/dataTables.bootstrap4.css') }}">
#section('js')
<!-- DataTables -->
<script src="{{ asset('adminlte/plugins/datatables/jquery.dataTables.js') }}"></script>
<script src="{{ asset('adminlte/plugins/datatables-bs4/js/dataTables.bootstrap4.js') }}"></script>
<script>
$(function () {
$("#example1").DataTable();
$('#example2').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
});
});
</script>
#endsection
#section('content')
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">DataTable User</h3>
#if ($message = Session::get('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h5><i class="icon fas fa-check"></i> Alert!</h5>
<p>{{ $message }}</p>
</div>
#endif
</div>
<!-- /.card-header -->
<div class="card-body">
<form action="{{ route('kwitansi.store') }}" method="POST" role="form" class="form-horizontal">
#csrf
<div class="form-group row">
<label for="name" class="control-label col-md-2">Terima Dari</label>
<div class="col-md-6">
<input type="text" name="received" class="form-control" placeholder="Received Form" />
</div>
</div>
<div class="form-group row">
<label for="registration" class="control-label col-md-2">Biaya Registrasi</label>
<div class="col-md-6">
<input type="text" name="registration" class="form-control" placeholder="Registration Fee" />
</div>
</div>
<div class="form-group row">
<label for="course" class="control-label col-md-2">Biaya Kursus</label>
<div class="col-md-6">
<input type="text" name="course" class="form-control" placeholder="Course Fee" />
</div>
</div>
<div class="form-group row">
<label for="trasnportation" class="control-label col-md-2">Biaya Transportasi</label>
<div class="col-md-6">
<input type="text" name="trasnportation" class="form-control" placeholder="Transportation Fee" />
</div>
</div>
<div class="form-group row">
<label for="payment" class="control-label col-md-2">Pembayaran Untuk</label>
<div class="col-md-6">
<input type="text" name="payment" class="form-control" placeholder="Payment Of" />
</div>
</div>
<div class="form-group row">
<label for="register_at" class="control-label col-md-2">Tanggal Registrasi</label>
<div class="col-md-6">
<input type="text" name="kota"class="form-control" value="Bandung" disabled hidden>
<input type="date" name="register_at"class="form-control">
</div>
</div>
<button type="submit" class="btn btn-primary" id="btnsubmit">Tambah Data</button>
<button type="reset" class="btn btn-warning" id="btncancel">Cancel</button>
</form>
<table id="example2" class="table table-bordered table-hover">
<thead>
<tr>
<th>No.</th>
<th>received</th>
<th>registration Fee</th>
<th>Course Fee</th>
<th>Transportation Fee</th>
<th>Grand Total</th>
<th>Payment of</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($kwitansi as $k)
<tr>
<td>{{ $k->id }}</td>
<td>{{ $k->received }}</td>
<td>{{ $k->registration }}</td>
<td>{{ $k->course }}</td>
<td>{{ $k->transportation }}</td>
<td>{{ $k->sum_rp }}</td>
<td>{{ $k->payment }}</td>
<td>
{{-- <i class="fas fa-edit"></i>
<i class="fas fa-file"></i>
<form action="{{ route('user.destroy', $u->id)}}" method="post">
#csrf
#method('DELETE')
<button class="btn btn-sm btn-outline-danger" type="submit"><i class="fas fa-trash-alt"></i></button>
</form> --}}
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>No.</th>
<th>received</th>
<th>registration Fee</th>
<th>Course Fee</th>
<th>Transportation Fee</th>
<th>Grand Total</th>
<th>Payment of</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
#endsection
I used form and view in one page are this is the problem
This is my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Kwitansi extends Model
{
// $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
protected $table = 'kwitansis';
protected $fillable = [
'received',
'registration',
'course',
'trasnportation',
'sum_rp',
'payment',
'register_at',
];
protected $primarykey = 'id';
public $increment = false;
protected $keyType = 'string';
}
Remove these lines from your model:
protected $primarykey = 'id';
public $increment = false;
protected $keyType = 'string';
Ok Thanks Guys For Helping, I Have Solved The Problem.
I Only Delete Some function on Controller adn Worked for Me
$request->validate([
'sum_rp' => 'required',
'sum_text' => 'required',
]);
$sum_rp = $request->registration + $request->course + $request->transportation;
function penyebut($nilai) {
$nilai = abs($nilai);
$huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
$temp = "";
if ($nilai < 12) {
$temp = " ". $huruf[$nilai];
} else if ($nilai <20) {
$temp = penyebut($nilai - 10). " belas";
} else if ($nilai < 100) {
$temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
} else if ($nilai < 200) {
$temp = " seratus" . penyebut($nilai - 100);
} else if ($nilai < 1000) {
$temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
} else if ($nilai < 2000) {
$temp = " seribu" . penyebut($nilai - 1000);
} else if ($nilai < 1000000) {
$temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
} else if ($nilai < 1000000000) {
$temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
} else if ($nilai < 1000000000000) {
$temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
} else if ($nilai < 1000000000000000) {
$temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
}
return $temp;
}
function terbilang($nilai) {
if($nilai<0) {
$hasil = "minus ". trim(penyebut($nilai));
} else {
$hasil = trim(penyebut($nilai));
}
return $hasil;
}
$sum_text = $request->sum_rp;
$kwitansi->sum_rp = $sum_rp;
$kwitansi->sum_text = terbilang($sum_text);
Only Delete This function and add it to Helper Class
I'm trying to fetch blogs using AJAX function in Laravel. But it is not working, neither showing any error. What I want is to display a load more button from where more blogs will be loaded using AJAX request. Here is my front-end code:
<div class="panel-body">
{{ csrf_field() }}
<div id="post_data"></div>
</div>
And my ajax script:
$(document).ready(function(){
var _token = $('input[name="_token"]').val();
load_data('', _token);
function load_data(id="", _token)
{
$.ajax({
url:"{{ route('loadmore.load_data') }}",
method:"POST",
data:{id:id, _token:_token},
success:function(data)
{
$('#load_more_button').remove();
$('#post_data').append(data);
}
})
}
$(document).on('click', '#load_more_button', function(){
var id = $(this).data('id');
$('#load_more_button').html('<b>Loading...</b>');
load_data(id, _token);
});
});
Here is my route:
web.php
Route::post('/loadmore', 'LoadMoreController#load_data')->name('loadmore.load_data');
Here is the controller function:
LoadMoreController.php
class LoadMoreController extends Controller
{
public function load_more(){
function load_data(Request $request)
{
if($request->ajax())
{
if($request->id > 0)
{
$data = DB::table('blogs')
->where('blog_id', '<', $request->id)
->orderBy('blog_id', 'DESC')
->limit(6)
->get();
}
else
{
$data = DB::table('blogs')
->orderBy('blog_id', 'DESC')
->limit(6)
->get();
}
$output = '';
$last_id = '';
if(!$data->isEmpty())
{
foreach($data as $row)
{
$output .= '
<div class="row">
<div class="col-md-12">
<h3 class="text-info"><b>'.$row->blog_title.'</b></h3>
<p>'.$row->blog_content.'</p>
<br />
<br />
<hr />
</div>
</div>
';
$last_id = $row->id;
}
$output .= '
<div id="load_more">
<button type="button" name="load_more_button" class="btn btn-success form-control" data-id="'.$last_id.'" id="load_more_button">Load More</button>
</div>
';
}
else
{
$output .= '
<div id="load_more">
<button type="button" name="load_more_button" class="btn btn-info form-control">No Data Found</button>
</div>
';
}
echo $output;
}
}
}
}
I'll be happy to provide any other details if needed or asked. Any suggestions/solutions will be highly appreciated.
Laravel version 8
web.php
Here is route file below:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/loadmore', [App\Http\Controllers\LoadMoreController::class, 'index']);
Route::post('/loadmore/load_data', [App\Http\Controllers\LoadMoreController::class, 'load_data'])->name('loadmore.load_data');
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>