Vue.js + Laravel - Delete object - javascript

I trying to build a CRUD using Vue.js and Laravel, but... I can Save, Read and Update the only problem is the Delete, can someone help me?
My index.blade.php: (to get id)
<div class="modal inmodal" id="delete" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content animated bounceInRight">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Fechar</span></button>
<h4 class="modal-title">Delete</h4>
</div>
<div class="modal-body">
<div class="form-group">
<p>Do you want delete this row <strong>ID: </strong> #{{competency.id}} <strong>Nome: </strong> #{{competency.name}} </p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" v-on:click="remove(competency.id)">Delete</button>
</div>
</div>
</div>
My Vue.js
var competency = new Vue({
el: '#competency',
filters: {
moment: function (date) {
return moment(date).format('DD/MM/YYYY');
}
},
data: {
competency: "",
searchQuery: '',
search: {
name: ""
},
list: [],
},
methods: {
fillCompetency: function(comp){
if (comp == null)
this.competency = {
id : "",
name : "",
description : "",
}
else
this.competency = comp;
},
del: function(index){
this.fillCompetency(this.list[index]);
$("#delete").modal('show');
},
remove: function(id){
var self = this;
self.competency._token = window.Laravel.csrfToken;
$.ajax({
url: "competency",
type: "POST",
dataType: 'json',
traditional: true,
data: id
}).done(function(data){
self.filter();
$("#delete").modal('hide');
fillCompetency(null);
});
}
},
mounted: function () {
this.filter();
},
watch: {
}
});
My Controller
class CompetencyController extends Controller {
public function __construct(){
$this -> middleware('auth');
}
public function index(){
return view('competency/index');
}
public function filter(){
$list = Competency::all();
return response()->json($list);
}
public function create(){
}
public function store(Request $request){
$entity = new Competency;
if ($request->id != null){
$entity = Competency::find($request->id);
}
if ($request->name == null && $request->description == null){
$entity = Competency::find($id);
return response()->json($entity->delete());
}
$entity->name = $request->name;
$entity->description = $request->description;
return response()->json($entity->save());
}
public function delete($id){
$entity = new Competency;
$entity = Competency::find($id);
return response()->json($entity->delete());
}
public function show($id){
}
public function edit($id){
}
public function update(Request $request){
}
public function destroy($id){
$entity = new Competency;
$entity = Competency::find($id);
return response()->json($entity->delete());
}
}
My route:
Route::resource('competency', 'CompetencyController');
The problem is, i have tried to send DELETE method on remove from Vue, but i get an error called 500 (Internal Error Serve) but on laravel.log dont show anything, i have tried send DELETE method because the desroy method is called correct? so i get error instead i send by POST method to store and check if just id is not null, if not i called method delete by laravel, so any method that i hev tried dont work, can someone help me?
I think that the error is on Route, but i tried everything too

Try changing your delete method to this
// your route for delete should be
Route::delete('competency/{id}', 'Controller#delete');
// controller
public function delete($id){
$responseMsg = "Competency not found";
$status = 404;
$entity = Competency::find($id);
if ($entity != null ){
$responseMsg = "Competency deleted";
$status = 204;
$entity->delete(); // delete method is void, doen't return any value
}
return response()->json(['message' => $responseMsg], $status);
}
Vue.js remove method
remove: function(id){
var self = this;
self.competency._token = window.Laravel.csrfToken;
$.ajax({
url: "competency/"+id,
type: "DELETE", //
traditional: true
// if you use POST method, data has to be a json object
// {id: id} then in laravel you could do $request->input('id');
}).done(function(data){
self.filter();
$("#delete").modal('hide');
fillCompetency(null);
});
}

Related

while creating tree node with popup modal getting error

here my goal is to create a tree on button click one popup modal has to opent where i have to input the values and and has to store in database and as well show in the tree,and also in the context menu which node we select there also an popup modal to open and get node ,delete node and renaming has to happen
here its my controller view
public class HomeController : Controller
{
private readonly ApplicationDbContext _db;
public HomeController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
return View();
}
//[HttpPost]
//public IActionResult Index(string selectedItems)
//{
// List<TreeViewModel> items=JsonConvert.DeserializeObject<List<TreeViewModel>>(selectedItems);
// return RedirectToAction("Index");
//}
public IActionResult GetTree()
{
List<TreeViewModel> nodes = new List<TreeViewModel>();
foreach (ParentClass type in _db.parent)
{
nodes.Add(new TreeViewModel
{
id = type.Id.ToString(),
parent = "#",
text = type.ParentName
});
}
foreach (ChildClass list in _db.child)
{
nodes.Add(new TreeViewModel
{
id = list.Id.ToString(),
parent = list.parentId.ToString(),
text = list.ChildName
});
}
return Json(nodes);
}
[HttpGet]
public IActionResult Create()
{
ParentClass parent = new ParentClass();
return PartialView("_HomePartial",parent);
}
[HttpPost]
public IActionResult Create(ParentClass parent)
{
if (ModelState.IsValid)
{
_db.parent.Add(parent);
_db.SaveChanges();
return PartialView("_HomePartial", parent);
}
return RedirectToAction("Index");
}
}
and my index view where i am giving button for popup modal to insert tree node in my code it taking only parent
<div class="container" id="placeHolder">
<div class="row">
<div class="col-3">
<div class="row pt-3">
<div class="col-6">
<p class="text-primary text-light">File Structure
</p>
</div>
<div class="col-6 text-end">
<button type="button" class="btn btn-primary"
data-toggle="ajax-modal" data-bs-target="#Addnode"
data-url="#Url.Action("Create")"><i class="bi
bi-plus-square-fill"></i></button>
</div>
</div>
<div id="simpleJsTree">
</div>
</div>
<div class="col=9">
</div>
</div>
</div>
javacript for tree view
$(document).ready(function () {
$.ajax({
async: true,
type: "GET",
url: "https://localhost:44376/Home/GetTree",
dataType: "json",
success: function (json) {
createJSTree(json);
}
});
});
function createJSTree(jsondata) {
$('#simpleJsTree').jstree({
"core": {
"check_callback": true,
'data': jsondata
},
"plugins": ["contextmenu"],
"contextmenu": {
"items": function ($node) {
var tree = $("#simpleJsTree").jstree(true);
return {
"Create": {
"separator_before": false,
"separator_after": true,
"label": "Create",
"action": function (obj) {
tree.create_node($node);
}
},
"Rename": {
"separator_before": false,
"separator_after": false,
"label": "Rename",
"action": function (obj) {
tree.edit($node);
}
},
"Remove": {
"separator_before": false,
"separator_after": false,
"label": "Remove",
"action": function (obj) {
tree.delete_node($node);
}
},
"Upload": {
"seperator_beore": false,
"seperator_after": false,
"label": "Upload"
}
};
}
}
}).bind('create_node.jstree', function (e, data) {
$.ajax({
url: "/Home/Create",
method: "POST",
data: data,
success: function (data) {
console.log(data);
}
});
});
}
here binding of create function to context menu is not working
this is the partial view where i m calling modal popup to take parent node
#model ParentClass
<div class="modal fade" id="Addnode">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"id="Addnode">Add Node</h4>
<button type="button" class="close" data-bs-
dismiss="modal">
<span>X</span>
</button>
</div>
<div class="modal-body">
<form asp-controller="Home" asp-action="Create"
method="post">
#Html.HiddenFor(m=>m.Id)
<div class="form-group">
<label asp-for="ParentName"></label>
<input asp-for="ParentName"class="form-
control" />
<span asp-validation-
for="ParentName"class="text-danger"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary"
data-save="modal">Save</button>
</div>
</div>
</div>
</div>
and site.js file to show modal popup
$(function () {
var placeElement = $('#placeHolder');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeElement.html(data);
placeElement.find('.modal').modal('show');
});
});
placeElement.on('click', '[data-save="modal"]', function
(event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
placeElement.find('.modal').modal('hide');
});
});
});
You are making ajax call with the codes:
var sendData = form.serialize();
$.post(actionUrl, sendData)
controller in MVC project read data from request form by default,So you need to add
[FromBody]
[HttpPost]
public IActionResult Create([FromBody]ParentClass parent)
{
_db.parent.Add(parent);
_db.SaveChanges();
return PartialView("_HomePartial", parent);
}
if you have further issue on the case,please show more details of the error

Multiple forms in #foreach loop. How do I submit one asynchronously with javascript. C# core Razor

Shopping cart with many items how to remove any item asynchronously with JavaScript this is my work so far. Can anyone improve on this?
your help would be greatly appreciated. Have a great day
Ok so this works if you remove items from the top of the list but fails if you remove items from some other place.
The problem seems to be that the form names are all the same "remove" without any indexing.
Problem is I'm not sure how to proceed with this.
document.forms['remove'].onsubmit = () => {
let formData = new FormData(document.forms['remove']);
fetch('/sales/cart?handler=RemoveItem', {
method: 'post',
body: new URLSearchParams(formData)
})
.then(() => {
var url = "/sales/cart?handler=CartPartial";
console.log(url)
$.ajax({
url: url,
success: function (data) {
$("#exampleModal .modal-dialog").html(data);
$("#exampleModal").modal("show");
//alert('Posted using Fetch');
}
});
});
return false;
}
<pre>
#foreach (var item in Model.Items)
{
<form name="remove" method="post">
<h4 class="text-left text-body">#item.Price.ToString("c")
<button class="btn btn-sm" title="Trash"><i style="font-size:large"
class="text-warning icon-Trash"></i></button>
</h4>
<input type="hidden" asp-for="#Model.Id" name="cartId" />
<input type="hidden" asp-for="#item.Id" name="cartItemId" />
</form>
}
</pre>
Update
----------
New markup
I added an index to the id and included an onclick event.
<form method="post" id="#i" onclick="removeItem(this.id)">
<button class="btn btn-sm" title="Trash">Item One</button>
<input type="hidden" asp-for="#Model.Id" name="cartId" />
<input type="hidden" asp-for="#item.Id" name="cartItemId" />
</form>
and create a new function that captured the form id including it in a constant.
<script>
function removeItem(formId) {
const form = document.getElementById(formId);
form.onsubmit = () => {
let formData = new FormData(form);
fetch('/sales/cart?handler=RemoveItem', {
method: 'post',
body: new URLSearchParams(formData)
})
.then(() => {
var url = "/sales/cart?handler=CartPartial";
console.log(url)
$.ajax({
url: url,
success: function (data) {
$("#exampleModal .modal-dialog").html(data);
$("#exampleModal").modal("show");
//alert('Posted using Fetch');
}
});
});
return false;
}
}
</script>
If anybody can improve on this please post it here.
Thanks.
Updates code behind Cart.cshtml.cs
using System;
using System.Threading.Tasks;
using Malawby.Models;
using Malawby.Services.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Malawby.Pages.Sales
{
public class CartModel : PageModel
{
private readonly ICartRepository _cartRepository;
public CartModel(ICartRepository cartRepository)
{
_cartRepository = cartRepository ?? throw new
ArgumentNullException(nameof(cartRepository));
}
[BindProperty]
public Cart Cart { get; set; } = new Cart();
public const string SessionKeyName = "_Name";
public string SessionInfo_Name { get; private set; }
public void OnGetAsync()
{
}
public async Task<PartialViewResult> OnGetCartPartialAsync()
{
var userName = GetUserName();
if (userName != null)
{
Cart = await _cartRepository.GetCartByUserName(userName);
}
return Partial("_ToCart", model: Cart);
}
private string GetUserName()
{
return HttpContext.Session.GetString(SessionKeyName);
}
public async Task OnPostRemoveItemAsync(int cartId, int cartItemId)
{
await _cartRepository.RemoveItem(cartId, cartItemId);
}
}
}
Update 2
This is the modified code I used. This is the error in the console.
XML Parsing Error: no root element found Location: localhost:44331/sales/cart?handler=RemoveItem Line Number 1, Column 1
There is no error on the page just nothing happens on the click of the trash can.
<script type="text/javascript">
function removeItem(cartItemId, cardId) {
var removeUrl = "/sales/cart?handler=RemoveItem";
$.post(removeUrl,
{
cartItemId: cartItemId,
cardId: cardId
})
.done(function (data) {
alert(data); //usually return true or false if true
remove card
$('#card_' + cardId).remove();
});
}
</script>
I am not familiar with asp.net core, but I will show how I usually do it without focusing on syntax.
first on the view no need to add multiple form but should use card id as index and delete button sent selected index like this:
#foreach (var item in Model.Items)
{
<div id="card_#item.cardId">
<h4 class="text-left text-body">#item.Price.ToString("c")
<button class="btn btn-sm" onclick="removeItem('#item.cardId') title="Trash"><i style="font-size:large"
class="text-warning icon-Trash"></i></button>
</h4>
</div>
}
then the script function will call remove api and remove selected card with no need to re-render the page:
<script type="text/javascript">
function removeItem(cardId) {
var removeUrl = "your apiUrl";
$.post( "removeUrl", { cardId: cardId })
.done(function( data ) {
alert( data ); //usually return true or false if true remove card
$('#card_'+ cardId).remove();
});
}
</script>

Partial view doesn't show validation message

I tried unobtrusiveValidation and that is not working for me, it's always breaking on
var unobtrusiveValidation = $form.data('unobtrusiveValidation');
var validator = $form.validate();
And every other solution online for partial view is not working, so what am I doing wrong?
View :
//BUNCH OF HTML
<!-- Modal edit user-->
#Html.Partial("~/Views/User/Partials/ProfileEditUserPartial.cshtml", Model.UserProfileData)
<div id="profileFormContainer" data-url="#Url.Action("ActionName", "ControllerName")"></div>
Partial view:
#model Web.Models.Users.Partials.ProfileEditUserPartialViewModel
<div class="modal fade text-left" id="profileEditUserModalId" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
#using (Html.BeginForm("UpdateUserData", "User", FormMethod.Post,new { id = "profileForm"}))
{
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel1">Edit</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.LabelFor(x => x.UserProfile.FirstName)*
#Html.TextBoxFor(x => x.UserProfile.FirstName, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.UserProfile.FirstName)
#Html.LabelFor(x => x.UserProfile.LastName)*
#Html.TextBoxFor(x => x.UserProfile.LastName, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.UserProfile.LastName)
#Html.LabelFor(x => x.UserProfile.Country)*
#Html.TextBoxFor(x => x.UserProfile.Country, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.UserProfile.Country)
</div>
<div class="modal-footer">
<button type="button" class="btn grey btn-outline-secondary" data-dismiss="modal">#Resources.Resource.General_Close</button>
<button type="button" class="btn btn-outline-success" data-addressId id="saveUserDataId">#Resources.Resource.General_Ok</button>
</div>
}
</div>
</div> </div>
Controller:
public ActionResult UpdateUserData(ProfileEditUserPartialViewModel userModel)
{
var model = PopulateProfileViewModel();
if (!ModelState.IsValid)
{
return PartialView("~/Views/User/Partials/ProfileEditUserPartial.cshtml", userModel);
}
m_UserService.UpdateUserProfile(userModel.UserProfile, GetUser().Id);
m_AccountService.ClearUserCache(GetUser());
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
Controller is like this because I was working with Ajax.beginForm, but let it be like this, that can be changed easily, and most important part is script file
Script:
$('#editUserDataId').click(function () {
$("#profileEditUserModalId").modal("show");
});
$('#saveUserDataId').click(function(){
var $formContainer = $('#profileFormContainer');
var url = $formContainer.attr('data-url');
$formContainer.load(url, function () {
var $form = $('#profileForm')
.removeData("validator")
.removeData("unobtrusiveValidation");
var unobtrusiveValidation = $form.data('unobtrusiveValidation');
var validator = $form.validate();
$.validator.unobtrusive.parse($form);
$form.submit(function () {
var $form = $(this);
if ($form.valid()) {
$.ajax({
url: url,
async: true,
type: 'POST',
data: JSON.stringify("Your Object or parameter"),
beforeSend: function (xhr, opts) {
},
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
$form.html(data);
$form.removeData('validator');
$form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($form);
}
});
}
return false;
});
});
return false;
});
So, I changed partial view:
<div class="modal-dialog" role="document">
<div id="profileInnerDivId" class="modal-content">
#using (Ajax.BeginForm("EditUserAddress", "User", new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "UserAddressUpdated",
InsertionMode = InsertionMode.Replace
}, new { data_accountid= #Model.AddressId }))
{
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel1">Edit</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.HiddenFor(x => x.AddressId)
#Html.LabelFor(x => x.Active)
#Html.RadioButtonFor(x => x.Active, true, new { #class = "opacity-fixed" })
</div>
<div class="modal-footer">
<button type="button" class="btn grey btn-outline-secondary" data-dismiss="modal">#Resources.Resource.General_Close</button>
<button type="submit" class="btn btn-outline-success" data-addressId id="saveEditBtnId">#Resources.Resource.General_Ok</button>
</div>
}
</div>
</div>
And in controller I am using Json:
[HttpPost]
public ActionResult EditUserAddress(UserAddress userAddress)
{
var model = PopulateProfileViewModel();
if (!ModelState.IsValid)
{
return PartialView("~/Views/User/Partials/_ProfileEditUserAddressPartial.cshtml", userAddress);
}
//some code...
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
And finally in my script I have swal that will be triggered and u just need to use HTML function to put code that is returned from action if error is occurred, so error msg will be displayed:
function UserAddressUpdated(result) {
var id = $(this).data('accountid');
if (result.success) {
$("#profileModalId").modal("hide");
swal({
title: Localization.Edit_User_Address_Success_Message,
icon: "success"
}).then(function () {
location.reload();
});
} else {
$("#profileModalId-" + id).html(result);
swal({
title: Localization.Edit_User_Address_Error_Message,
icon: "error"
});
}
}
Concept:
1. Use Ajax.BeginForm, define Success method
2. In Action use Json return type and if error occurred, return that
partial view
3. Use $('divId').html to write your msg.

Get the article's view times using Vue.js and Laravel 5.3

My thought process:
When the show page opens, get the article's id with JavaScript.
Check this id exist or not in cookie
If not exists, write it into cookie and send an ajax request, the backend updates view times.
If exists, do nothing.
Demo:
View:
<div class="card">
<div class="card-block text-xs-center">
<h5 class="card-title">{{$article->title}}</h5>
<hr class="m-y-2">
<h6 class="card-subtitle text-muted">date:{{$article->created_at->format('Y-m-d')}}
    views:{{$article->view_times}}</h6>
</div>
<div class="card-block">
<p class="card-text">{{$article->content}}</p>
</div>
</div>
Controller:
class ArticlesController extends Controller
{
//`show` method
public function show($id)
{
$article = Article::findOrFail($id);
return view('show', compact('article'));
}
//the method of updating view times.
public function statistics(Request $request)
{
$id = $request->input('id');
$article = Article::findOrFail($id);
$view_time=$article->view_time;
$article->view_time=$view_time+1;
$article->save();
}
}
JavaScript:
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name=csrf-token]').getAttribute('content')
Vue.http.options.emulateJSON = true;
var vm = new Vue({
el: "body",
data: function(){
return{
id:[]
}
},
created() {
//1、Get the article's id.Do I have to send an ajax request? Is there any other way?
this.$http.get('article/get-id').then((response) => {
// success callback
this.id=response.data;
}, (response) => {
// error callback
});
//2、After Getting the `id`,check it in cookie,I don't know how to do it?
//3、If not exists,write it into cookie and send an ajax request,how to write the if() sentence?
if(){
var formData = new FormData();
var id=this.id;
formData.append('id',id);
this.$http.patch('article/statistics', formData,{
before(request) {
if (this.previousRequest) {
this.previousRequest.abort();
}
this.previousRequest = request;
}
}).then((response) => {
// success callback
}, (response) => {
// error callback
});
}
}
});
Questions:
There are three questions, shown as comments in JavaScript code above.

AngularJS configuring the persistence layer interaction

I currently have a very simple application which initially calls a php file to get data and then iterate through the dataset and create a table. Within the table I have an "Enable/Disable" button which when clicked would update the model, which in turn would push to the persistence layer. The issue I am running into is that while I am able to update the model which updates the view nicely, I am unable to figure out how to get the persistence layer part of it working. I added two custom functions for the service "enable/disable" to reflect the button click event, but am not really sure if I am heading in the correct direction or not but my code is below.
The View partial:
<table class="table table-hover">
<thead><tr><th>Name</th><th>Username</th><th>Details</th><th>Facility</th><th>Last Login</th><th>Days from last login</th></tr></thead>
<tbody>
<tr ng-class="{'error':user._accountDisabled,'success':user._accountDisabled==false}" ng-repeat="user in users | filter:query | orderBy:orderProp">
<td>{{user._firstName}} {{user._lastName}}</td>
<td>{{user._userName}}</td>
<td><a class="btn btn-primary" href="#/userExceptions/{{user._userName}}">Details</a></td>
<td>{{user._facilityName}}</td>
<td>{{user._hrLastLogon}}</td>
<td>{{user._daysLastLogon}}</td>
<td>
<ng-switch on="user._accountDisabled">
<button ng-switch-when=true class="btn btn-primary" ng-click="enable(user)">Enable</button>
<button ng-switch-when=false class="btn btn-danger" ng-click="disable(user)">Disable</button>
</ng-switch>
</td>
</tr>
</tbody>
</table>
The custom service for persistence:
angular.module('userServices', ['ngResource']).
factory('User', function($resource) {
return $resource('userActions.php', {}, {
query: {method: 'GET', params: {userName: 'userName'}, isArray: true},
enable: {method: 'GET',params: {action: 'enable', userName: 'userName'}}},
disable: {method: 'GET', params: {action: 'disable', userName: 'userName'}}
});
});
Finally the controller:
function UserExceptionsCtrl($scope, User) {
$scope.users = User.query();
$scope.orderProp = '_firstName';
$scope.enable = function(user) {
$scope.user = user;
$scope.user._accountDisabled = false;
$scope.user.$save();
User.enable({userName:user._userName});
};
$scope.disable = function(user) {
$scope.user = user;
$scope.user._accountDisabled = true;
$scope.user.$save();
User.disable({action: 'disable', userName: self._userName});
};
}
EDIT As requested server side code:
The useractions file processes the request and creates mappers to retrieve a user object. From the user object it updates the necessary property and saves it in the persistence layer.
userActions.php
$username = (isset($_REQUEST['userName']) ? $_REQUEST['userName'] : '');
$action = (isset($_REQUEST['action']) ? $_REQUEST['action'] : '');
require 'library/autoloader/src/autoload.php';
try {
$ADUserMapper = new UserMapper(new LDAPAdapter());
switch ($action) {
case 'enable':
$ADUserEditMapper = new UserMapper(new LDAPAdapter());
$user = $ADUserEditMapper->findByUsername($username);
if ($user) {
$user->enableADAccount();
$ADUserEditMapper->updateUAC($user);
}
break;
case 'disable':
$ADUserEditMapper = new UserMapper(new LDAPAdapter());
$user = $ADUserEditMapper->findByUsername($username);
if ($user) {
$user->disableADAccount();
$ADUserEditMapper->updateUAC($user);
}
break;
default:
$adapter = new PdoAdapter();
$employeeDBMapper = new EmployeeMapper($adapter);
$ADUsers = $ADUserMapper->findMultipleUsers(array('objectClass' => 'user'), "OU=Users,DC=domain,DC=com", TRUE);
$exceptions = array();
foreach ($ADUsers as $user) {
$employee = $employeeDBMapper->findByUserName($user->userName);
if (!$employee) {
array_push($exceptions, $user);
}
}
$result = array();
foreach ($exceptions as $user) {
array_push($result, $user->getExceptionData());
}
echo json_encode($result);
break;
}
} catch (Exception $e) {
echo json_encode(array('error' => true, 'errorMessage' => $e->getMessage()));
}

Categories