How to delete a record in octobercms? - php

I am a bit confused how it comes together. I am trying to delete a record from a list of records and I currently have this.
function onDelete()
{
$recordId = post('record')
$record = Advert::find($recordId);
$record->delete();
}
In twig i have
<tbody>
{% for post in posts %}
<td>{{ post.title }}</td>
<td><button class="btn btn-sm btn-danger" data-request ="onDelete" data-request-confirm="Are you sure" data-request-success="alert('Successfully Deleted')">Delete</button> </td>
</tr>
{% endfor %}
</tbody>
I am currently having this error
"Call to a member function delete() on null"

You're not sending the record ID to the server in your AJAX request.
Add data-request-data="record: {{ post.id }}" to your button that triggers the AJAX request so that post('record') actually gets data from the AJAX request that it can use to find the record that you want to delete.

Make sure to use field names when querying.
Try this.
function onDelete()
{
$recordId = request('post')
Advert::where('slug',$recordId)->delete();
}
If not add die() and use print_r to check whether Advert::where is returning any object.

Related

How to get ID from symfony Form Field to fill out rest of form

I would appreciate any kind of help for this problem I'm having.
I have 2 Symfony Forms :
One for the search part (Serial Number)
Another form that will be filled out if the Serial Number exists.
I need to get dynamicly the value of the ID.
Here is a snippet of my code :
{% for ClientInfo in getInstallationClientBySerialNumber %}
<tr id="ClientInfo_{{ installClientInfo.idRma }}">
<td>{{ ClientInfo.numeroSerie }}</td>
{% endfor %}
The loop works but I'm struggling with the JQuery part to get the ID. I've tried :
$("#client_sn").click(function(){
var elmId = $("#ClientInfo_id").attr("id");
alert(elmId);
});
Any help would be very kind.
Many Thanks in advance.
HTML ID's have to be unique on a page. You're looping over multiple elements, giving them all the same ID "client_sn"
What you can do with Twig in a for loop is access loop.index as a counter
https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable
{% for ClientInfo in getInstallationClientBySerialNumber %}
<tr id="ClientInfo_{{ installClientInfo.idRma }}">
<td>{{ ClientInfo.numeroSerie }}</td>
{% endfor %}
In the jQuery you can then use a pattern to match all elements with an ID starting client_sn:
$("a[id^='client_sn']").click(function(){
var elmId = $("#ClientInfo_id").attr("id");
alert(elmId);
});
https://api.jquery.com/attribute-starts-with-selector/
Or use some other selector to identify the links.
Alternatively instead of {{loop.counter}} you could reuse the installClientInfo.idRma ID you're also using:
{% for ClientInfo in getInstallationClientBySerialNumber %}
<tr id="ClientInfo_{{ installClientInfo.idRma }}">
<td>{{ ClientInfo.numeroSerie }}</td>
{% endfor %}

Problem with displaying data that I want to delete with many to many relationship in Laravel

I have many to many relationship between users and products table and I set up a view (welcome.blade.php) that when I click on the product name, which is a link, it is supposed to redirect me to page where my delete form is so I can delete that particular product, but I get 404 not found page. I suspect that error is somewhere in my routes but I can't seem to find the problem. Also when I click on some product my url says project/destroy/1 which I think is good. Here is my code:
web.php:
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/store', 'HomeController#store')->name('store');
Route::delete('/destroy/{$id}', 'HomeController#destroy')->name('destroy');
destroy.blade.php:
<div class="col-md-12">
<form action="destroy/{{ $product->id }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
welcome.blade.php:
#if($products)
<table class="table">
<thead>
<th>#</th>
<th>Product Name</th>
<th>Owner Of The Product</th>
<th>Created At</th>
</thead>
<tbody>
#foreach ($products as $product)
<tr>
<td>{{ $product->id }}</td>
<td>
{{ $product->files }}
</td>
<td>
#foreach ($product->users as $user) {{ $user->name }}
#endforeach
</td>
<td>{{ date('M j, Y', strtotime($product->created_at)) }}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
HomeController.php:
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class HomeController extends Controller
{
public function destroy(Product $product)
{
$product->users()->detach();
$product->delete();
return view('destroy');
}
}
You defined the following route in your file.
Route::delete('/destroy/{$id}', 'HomeController#destroy')->name('destroy');
This creates a DELETE route. DELETE routes are meant to be accessed by APIs. Links in anchor tags use GET routes. Clicking on
{{ $product->files }}
makes the router try and match GET /destroy/{$id} which is not defined, so it throws either an exception if debug is on or a 404 if not. You can see this in action by looking at the network tab of your browser's developer console.
Unless you add another GET route, you'll keep getting 404s.
Route::get('/destroy/{$id}', 'HomeController#destroy')->name('product.destroy-form');
will make the following link work.
{{ $product->files }}
Also, in the destroy method you're returning the view without passing any variables but in destroy.blade.php you seem to be using $product. Don't forget to add it!
You are nearly there, you just have a step too many.
Good call on the form and using the delete method, this is absolutely what you are supposed to do
However where you are going wrong is in using the link to go to a separate page with the form on to delete. You are better using a little javascript so the link submits a hidden form from the link.
<a onclick="document.getElementById('delete-form-{{$product->id}}').submit();}">{{ $product->files }}</a>
<form id="delete-form-{{$product->id}}" action="{{ route('destroy', ['id' => $product->id]) }}" method="POST" style="display: none;">
#csrf
#method('delete')
</form>
You can do the method you have but you need an additional route::get request to a page that loads the form and then you can submit the form on that page to delete.
I think it is because to delete a product using a new page the first thing to do is navigate to that page which you are not doing. You are instead going directly to the delete function using this
Route::delete('/destroy/{$id}', 'HomeController#destroy')->name('destroy');
You need to define a route that lets you go to that page first which u can do by creating a route like this:
Route::get('/delete/{$id}', 'HomeController#delete')->name('delete');
You should create a new function delete in the HomeController that just returns the destroy.blade.php. Something like this.
$product= Product::find($id);
return view('destroy')->with('product', $product);
where $id is the product id and Product is the model that you are using.

Laravel 5 getting ID from URL

I have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.
#foreach ($patients as $patient)
<tr>
<td>{{ $patient->pID }}</td>
<td>{{ $patient->pName }}</td>
<td>{{ $patient->pAddress }}</td>
<td>{{ $patient->pBday }}</td>
<td>{{ $patient->pPhone}}</td>
<td>{{ $patient->pEcon }}</td>
<td>{{ $patient->pDreg }}</td>
<td></td>
<td>
<a href="{{ URL::to('visit/'.$patient->pID) }}">
<img src="../images/viewvisit.png" style="width:30px; height:30px;">
</a>
</td>
<td>
<a href="{{ URL::to('addeditvisit/'.$patient->pID) }}">
<img src="../images/visit.png" style="width:30px; height:30px;">
</a>
</td>
<td>
<a href="{{ URL::to('editpatient/'.$patient->pID) }}">
<img src="../images/update.png" style="width:30px; height:30px;">
</a>
</td>
<td>
<a href="{{ URL::to('deletepatient/'.$patient->pID) }}">
<img src="../images/delete.png" style="width:30px; height:30px;">
</a>
</td>
</tr>
#endforeach
what I want is to get the id from the URL and put it in a variable so that I can utilize it my other page.
I'm currently stuck with this controller function.
public function index(Request $request) {
$doctors = Doctor::where('dStatus', 0)
->lists('dName', 'dID');
$beds = Bed::where('bStatus', 0)
->lists('bName', 'bID');
$patient = Patient::patient();
// $uri = $request->path('patient');
return View::make('pages.addeditvisit', [
'doctors'=>$doctors,
'beds'=>$beds,
'patient'=>$patient->pID
]);
}
This is late. But for the benefit of others like me;
If you do not have to do it in a method like the answers above have shown, As of Laravel 5.0 (Not sure about previous versions), you can do
$request->route('id');
That returns the value of the id parameter on the route.
Or just use it within Blade: {{ request()->route('id') }}
Basically when you are defining the routes, you use something called route parameters, something like this
Route::get('/visit/{id}', 'Controller#someMethod');
This id will be available as a parameter in your handler funtion,
public function someMethod($id) {
// you have the id here
}
Simple example:
as link=> example.com/user/1
as rout=> Route::get('user/{id}', 'UserController#user');
as UserController function
public function user($id){
echo $id;
}
output => 1
The trick is to declare the url's structure at routes including the id, for example:
// {{ URL::to('editpatient/'.$patient->pID) }}
Route::get('editpatient/{patientId}', 'MyController#index');
Then, just inject the id in the controller's function:
public function index($patientId){
// $patientId is the variable from url
}
Please refer to the answered question for how to get a parameter from a route. But if you stumbled on this old Laravel thread looking for how to retrieve a model by its ID, the simplest way is to instantiate the model in the controller's request parameter:
Route::get('/retrieve_product/{product}', 'SearchController#getProduct');
Then over in your controller, you simply need:
use App\Product;
class SearchController extends Controller
{
public function getProduct( Product $product ) {
return $product;
}
}
That's it. No find, no where, no get, no first etc.
So, in this example, if you visit /retrieve_product/1 the first product is returned to you.
Route::get('post/user/{id}','ProductController#allpost')->where('id', '[0-9]+');
Controller
public function allpost($id)
{
$products = Product::where('uploadby', $id)->orderBy('created_at','desc')->paginate(5); <br>
return view('product.user_product')->with('products', $products);
}

json_encode doens't work in my Symfony2's controller

I'm new in Symfony2 and AngularJS. I´m trying to use json_encode to show my database's content. But it doens't work. This is my controller:
public function catalogonewAction()
{
$data = $this->getDoctrine()->getManager()
->getRepository('AcmeRetroBundle:Game')->findAll();
return $this->render('AcmeRetroBundle:Default:catalogonew.html.twig',
array('data' => json_encode($data)));}
This is my html.twig:
{% verbatim %}
<div ng-app="myApp1" ng-init="mydata = {{ list|raw }}">
<table id="sortedData">
<tr><th>T1</th><th>T2</th></tr>
<tr ng-repeat="data in mydata | filter:sortData">
<td>{{data.nombreJuego}}</td>
<td>{{data.description}}</td>
</tr>
</table>
</div>
{% endverbatim %}
And my app.js:
angular.module('myApp1', []).
filter('sortData', function() {
alert('Hi');
return out;
});
When I refresh my page it is shown this:
T1 T2
{{data.nombreJuego}} {{data.description}}
What is wrong?
I don't like to pass data from back-end to an
anuglarJS like that, it's a common to use ajax request to retrieve data.
Try to pass you data to a javascript variable that you could affect is to an object in you angular scope :
<script>
var list= {{ data }}
</script>
{% verbatim %}
<div ng-app="myApp1" ng-init="mydata = list">
<table id="sortedData">
<tr><th>T1</th><th>T2</th></tr>
<tr ng-repeat="data in mydata | filter:sortData">
<td>{{data.nombreJuego}}</td>
<td>{{data.description}}</td>
</tr>
</table>
</div>
{% endverbatim %}

I cannot get value from an object in blade template Laravel 4

I have a loop foreach in a blade template where i print data from a specific model, the problem is I am not able of getting the value of "$pedido->proveedor()->first()->name" in the code giveing me this error "ErrorException (E_UNKNOWN) Trying to get property of non-object (View: C:..":
#foreach($pedidos as $pedido)
<tr>
<td>
{{ $pedido->id }}
</td>
<td>
{{ $pedido->proveedor()->first()->name }}
</td>
<td>
{{ date('d/m/Y', $pedido->fecha) }}
</td>
<td>
<a onclick="return confirm('deseas borar este registro?')" class="btn btn-danger btn-xs fullButton">Borrar</a>
</td>
</tr>
#endforeach
The weird thing here is when I code this "$pedido->proveedor()->first()" in side the loop of the template I get an object like this:
{"name":"nombre","domicilio":"domicilio","cp":"46006","poblacion":"poblacion","ciudad":"ciudad","pais":"pais"}
but coding this "$pedido->proveedor()->first()->name" I get the error:
the data is sent from a controller:
public function listPedidos()
{
$pedidos = Pedido::all();
// this next pice of code shows me i can get the name as spected but only from php
// foreach($pedidos as $pedido){
// ddd($pedido->proveedor()->first()->name);exit;
// }
return View::make('pedidos/pedidos-list')->with('pedidos', $pedidos);
}
Another weirder thing is that I have the same code with different model and it is working.
Thanks in advance for any help. ;)
You should use:
{{ $pedido->proveedor->name }}
Problem solved:
the previos answer was ok. I can use:
{{ $pedido->proveedor()->first()->name }}
or
{{ $pedido->proveedor->name }}
but because in one of the way of the loop there was not content to refer to i.e($pedido->proveedor didn't exixt) I use this:
{{ isset($pedido->Proveedor->name )?$pedido->Proveedor->name :''; }}

Categories