I am having this issue where I'm only able to get the error message. I have some tables where student id is the foreign key, however even thou the id number is not any of the tables it still gives the message "You cannot delete this Student" but won't pass there if it can be deleted
public function findBystudentid($studentid)
{
$record= $this->getEntityManager()->getRepository('AcmeDemoBundle:record')->findBy(['studentid' => $studentid]);
$lecture = $this->getEntityManager()->getRepository('AcmeDemoBundle:lecture')->findBy(['studentid' => $studentid]);
$faculty = $this->getEntityManager()->getRepository('AcmeDemoBundle:faculty')->findBy(['studentid' => $studentid]);
if ($record||$lecture||$faculty){
return true;
} else {
return false;
}
}
public function deleteAction(Request $request, $studentid)
{
$form = $this->createDeleteForm($studentid);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$deletable = $em->getRepository('AcmeDemoBundle:Student')->findBystudentid($studentid);
if ($deletable) {
$this->addFlash('error','ERROR! You cannot delete this Student' );
}
else
{
$em->remove($deletable);
$em->flush();
$this->addFlash('error','Student Deleted');
}
return $this->redirect($this->generateUrl('Student'));
}
First, your naming is a bit off. You need to fix it as it tends to be a bit confusing. With that in mind, I suggest you do it like this:
1. Controller method to check if student is deletable:
private function isStudentDeletable($studentid)
{
$em = $this->getEntityManager();
$record= $em->getRepository('AcmeDemoBundle:record')->findBy(['studentid' => $studentid]);
if ( $record ){
return false;
}
$lecture = $em->getRepository('AcmeDemoBundle:lecture')->findBy(['studentid' => $studentid]);
if ( $lecture ){
return false;
}
$faculty = $em->getRepository('AcmeDemoBundle:faculty')->findBy(['studentid' => $studentid]);
if ( $faculty ){
return false;
}
return true;
}
2. Controller's action to invoke the above
public function deleteAction(Request $request, $studentid)
{
$form = $this->createDeleteForm($studentid);
$form->handleRequest($request);
$deletable = $this->isStudentDeletable($studentid);
if (!$deletable) {
$this->addFlash('error','ERROR! You cannot delete this Student' );
}
else
{
$em = $this->getDoctrine()->getManager();
$student = $em->getRepository('AcmeDemoBundle:Student')->find($studentid)
$em->remove($student);
$em->flush();
$this->addFlash('error','Student Deleted');
}
return $this->redirect($this->generateUrl('Student'));
}
Hope this help and clarifies a bit.
I think you are calling findBystudentid wrong because findBystudentid is not in the Entity.
Here is the updated version
public function deleteAction(Request $request, $studentid)
{
$form = $this->createDeleteForm($studentid);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$deletable = $this->findBystudentid($studentid);
if ($deletable) {
$this->addFlash('error','ERROR! You cannot delete this Student' );
} else {
$em->getRepository('AcmeDemoBundle:Student')->findBy(['studentid' => $studentid])
$em->remove($deletable);
$em->flush();
$this->addFlash('error','Student Deleted');
}
return $this->redirect($this->generateUrl('Student'));
}
Also findBystudentid should be a private function
private function findByStudentId() ...
Related
I want to add to the wishlist; after I click add, I get an error. I believe that the way I want to access the product is wrong.
public function addToFavorie($id)
{
$user = Auth::user();
$product = produit::find($id);
if (!$product || !$user) {
abort(404);
}
// I believe this is the part responsible for the error
$favorie = $user->favorie;
$favprds = $favorie->produits;
//
for ($i = 0; $i < count($favprds); $i++) {
if ($favprds[$i]->id == $id)
return redirect()->back()
->with('error', 'produit deja dans votre favorie');
}
$favorie->produits()->attach($product->id);
return redirect()->back()->with('info', 'produit ajoute a votre favorie');
}
Model
public function user()
{
return $this->belongsTo("App\Models\User");
}
public function produits()
{
return $this->belongsToMany('App\Models\Produit', 'produits_favories');
}
I tried this in the controller, and it returned 404.
$user = Auth::user()->favorie;
$product = produit::find($id);
if (!$product || !$user) {
abort(404);
}
$favprds = $favorie->produits;
Instead of Using "belongsToMany" in
public function produits() { return $this->belongsToMany('App\Models\Produit', 'produits_favories'); }
use "hasMany" like this
public function produits() { return $this->hasMany('App\Models\Produit', 'produits_favories'); }
It should work
public function addToFavorie($id)
{
$product = produit::findOrFail($id);
$favorie = Favorie::firstOrCreate([
'user_id' => auth()->id()
], [
/* attributes for a `Favorie` instance */
]);
$favorie->produits()->syncWithoutDetaching($product->id);
return redirect()->back()->with('info', 'produit ajoute a votre favorie');
}
This is my previous post: Laravel inserting normal image, value become null
Thank you for everyone giving me advise in previous post. Now I got another question. I would like to ask for help and teach me with this issues.
I currently want to save the image path in my database. As the previous post mentioned before. My database now is saving value 1 instead of the path. here is my function upload code.
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->image = \Storage::disk('public')->put('image', Request::file('image'));
$url = Storage::url('image');
$url= urldecode(string ($url));
$url->save();
$task->save();
return redirect('/');
}
I also want to display this in my welcome.blade.php. So, what would I add and change?
This is all my code:
public function index()
{
$user = Auth::user();
return view('welcome',compact('user'));
}
public function add()
{
return view('add');
}
public function create(Request $request)
{
$task = new Task();
$task->description = Request::get('description');
$task->user_id = Auth::id();
$flagInserted = \Storage::disk('public')->put('image', Request::file('image'));
$url = '';
if ($flagInserted) {
$url = Storage::url('image');
}
$task->image = $url;
$duplicate = Task::where('description',Request::get('description'))->first();
if($duplicate)
{
print_r("The data is exists");
}
else
{
$task->save();
}
return redirect('/');
}
public function edit(Task $task)
{
if (Auth::check() && Auth::user()->id == $task->user_id)
{
return view('edit', compact('task'));
}
else {
return redirect('/');
}
}
public function update(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->description = Request::get('description');
$task->save();
return redirect('/');
}
}
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$flagInserted = \Storage::disk('public')->put('image', Request::file('image'));
$url = '';
if ($flagInserted) {
$url = Storage::url('image');
}
$task->image = $url;
$task->save();
return redirect('/');
}
}
public function storeTask(){
$task= new Task();
$task->name = request('name');
$task->description = request('description');
$task->image = request('image');
$task->save();
return redirect('/task');
}
I have read the Laravel page. But not really sure and how can I able solve this problem.
below will return 1 or 0, if file is saved or not. That's why it is inserting 1 into your databse:
\Storage::disk('public')->put('image', Request::file('image'))
Once successfully saved, To fetch file url, you can use below code:
$url = \Storage::url('file.jpg');
So your code will be:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileuploadController extends Controller
{
//
public function index() {
return view('fileupload');
}
public function save(Request $request) {
$image = $request->file('image');
$fileName = time() . '.' . $image->getClientOriginalExtension();
$img = \Image::make($image->getRealPath());
$img->stream(); // <-- Key point
$flagInserted = \Storage::disk('public')->put($fileName, $img);
$url = '';
if ($flagInserted) {
$url = \Storage::url('app/public/' . $fileName);
}
dd($url);
}
}
If you face error like 'Class Image' not found that do as follow:
composer require intervention/image
You file will be saved in 'storage/app/public folder'.
If you file is not saved than please permission and allow permission your project folder.
have you try this.? Request::file to $request->file
and
replce Illuminate\Support\Facades\Request to use Illuminate\Http\Request;
ref link https://laravel.com/docs/6.x/filesystem#file-uploads here you can see
use Illuminate\Http\Request; is imported not Illuminate\Support\Facades\Request
public function upload(Request $request, Task $task)
{
if (isset($_POST['delete'])) {
$task->delete();
return redirect('/');
} else {
$task->image = \Storage::disk('public')->put('image', $request->image);
$task->save();
return redirect('/');
}
}
ref link https://laravel.com/docs/6.x/filesystem#storing-files
and to print image inside blade
you can use Storage::url() function on laravel
EX : Storage::url($task->image) // here image value is coming from task table data
ref link https://laravel.com/docs/6.x/filesystem#file-urls
I have created a search form,i'm trying to fetch the following data from the database (airport,airport1,departuredate,price),i can only get [airport] but not the other entity.
This is my controller:
public function searchtabflightResultAction(Request $request)
{
$form = $this->createForm(new SearchflightType());
if ($this->get('request')->getMethod() == 'POST')
{
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('FLYBookingsBundle:Post')->searchflight($form['airport']->getData());
} else {
throw $this->createNotFoundException('The page you were looking for doesn\'t exist.');
}
return $this->render('FLYBookingsBundle:Post:searchtabflightResult.html.twig', array('entities' => $entities));
}
PostRepository.php
public function searchflight($entity)
{
$qb = $this->createQueryBuilder('u')
->select('u')
->where('u.airport like :entity')
->andWhere('u.airport1 like :entity')
->orderBy('u.id')
->setParameter('entity', '%'.$entity.'%');
return $qb->getQuery()->getResult();
}
Try something like :
In your controller:
$entities = $em->getRepository('FLYBookingsBundle:Post')->searchflight($form);
In your repo:
public function searchflight(FormInterface $form)
{
$qb = $this->createQueryBuilder('u');
if ($form->has('airport')) {
$qb->andWhere(
$qb->expr()->like('u.airport', ':airport')
)
->setParameter('airport', '%'. $form->get('airport')->getData().'%')
}
// ... complete like this with the other params
I am new to ZF2 application. I trying the documentation part as n practice provided in ZF2 doc. Working on album module it is find with the other parts but as it comes to delete. My delete album part is not working and also not showing any error as well
My files for delete code as
//src/Album/Model/AlbumTable.php
namespace Album\Model;
use Zend\Db\TableGateway\TableGateway;
Class AlbumTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getAlbum($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id'=> $id));
$row = $rowset->current();
if(!$row)
{
throw new Exception("Could not find row - $id");
}
return $row;
}
public function saveAlbum(Album $album)
{
$data = array(
'artist' => $album->artist,
'title' => $album->title,
);
$id = (int) $album->id;
if($id == 0)
{
$this->tableGateway->insert($data);
}
else
{
if($this->getAlbum($id))
{
$this->tableGateway->update($data, array('id' => $id));
}
else
{
throw new \Exception("Album ID does not exists");
}
}
}
public function deleteAlbum($id)
{
$this->tableGateway->delete(array($id => (int) $this->id));
}
}
Other Album Controller file is as
//src/Album/Controller/AlbumController.php
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Album\Model\Album; // For the Form Display
use Album\Form\AlbumForm; // album manipulation form view
Class AlbumController extends AbstractActionController
{
protected $albumTable;
public function getAlbumTable()
{
if(!$this->albumTable)
{
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
}
public function indexAction()
{
//Albums Retreiving from Model and Passing to View for listing the albums
return new ViewModel(array(
'albums' => $this->getAlbumTable()->fetchAll(),
));
}
public function addAction()
{
$form = new AlbumForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if($request->isPost())
{
$album = new Album();
// printf($form);die();
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if($form->isValid())
{
$album->exchangeArray($form->getData());
$this->getAlbumTable()->saveAlbum($album);
//Redirect to list of albums
$this->redirect()->toRoute('album');
}
}
return array('form' => $form);
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id',0);
if(!$id)
{
return $this->redirect()->toRoute('album',array(
'action' => 'add'
));
}
// Get the Album with the specified id. An exception is thrown
// if it cannot be found, in which case go to the index page.
try
{
$album = $this->getAlbumTable()->getAlbum($id);
}
catch(\Exception $ex)
{
return $this->redirect()->toRoute('album', array(
'action' => 'index'
));
}
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if($request->isPost())
{
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if($form->isValid())
{
$this->getAlbumTable()->saveAlbum($album);
//Redirect to list all albums
return $this->redirect()->toRoute('album');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
public function deleteAction()
{
$id = (int) $this->params()->fromRoute('id',0);
if(!$id)
{
return $this->redirect()->toRoute('album');
}
$request = $this->getRequest();
if($request->isPost())
{
$del = $request->getPost('del','No');
if($del=='Yes')
{
$id = (int)$request->getPost('id');
$this->getAlbumTable()->deleteAlbum($id);
}
//Redirect to list of Albums
return $this->redirect()->toRoute('album');
}
return array(
'id' => $id,
'album' => $this->getAlbumTable()->getAlbum($id),
);
}
}
Deleting File view as follows
//view/album/album/delete.phtml
$title = "Delete Album";
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<p>
Are you sure want to delete the album
'<?php echo $this->escapeHtml($album->title); ?>' By
'<?php echo $this->escapeHtml($album->artist); ?>' ??
</p>
<?php
$url = $this->url('album', array(
'action' => 'delete',
'id' => $this->id,
));
?>
<form action='<?php echo $url; ?>' method='post'>
<div>
<input type='hidden' name='id' value='<?php echo (int)$album->id; ?>'/>
<input type='submit' name='del' value='Yes'/>
<input type="submit" name="del" value='No'/>
</div>
</form>
When i'm trying to delete the album it askes for confirmation and when pressed as yes it get to album lists again showing the same record within the lists.
Maybe you are having problem with the first files itself for delete operation
In your //src/Album/Model/AlbumTable.php file
You stated the deleteAlbum function as
public function deleteAlbum($id)
{
$this->tableGateway->delete(array($id => (int) $this->id));
}
Rewrite the code as
public function deleteAlbum($id)
{
$this->tableGateway->delete(array('id' => (int) $id));
}
Hopefullly this was the only problem as you said it doesn't showing any error or at least exception.
I am super new to doctrine and I just converted the Akrabat album rest api example to work with doctrine and it works well to show the data. But when i edit, delete or add albums it throws an error which says,
Fatal error: Call to undefined method Zend\Http\PhpEnvironment\Request::post()
Here's is my controller,
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController,
Zend\View\Model\ViewModel,
Album\Form\AlbumForm,
Doctrine\ORM\EntityManager,
Album\Entity\Album;
class AlbumController extends AbstractActionController
{
protected $em;
public function setEntityManager(EntityManager $em)
{
$this->em = $em;
}
public function getEntityManager()
{
if (null === $this->em) {
$this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->em;
}
public function indexAction()
{
return new ViewModel(array(
'albums' => $this->getEntityManager()->getRepository('Album\Entity\Album')->findAll()
));
}
public function addAction()
{
$form = new AlbumForm();
$form->get('submit')->setAttribute('label', 'Add');
$request = $this->getRequest();
if ($request->isPost()) {
$album = new Album();
$form->setInputFilter($album->getInputFilter());
$form->setData($request->post());
if ($form->isValid()) {
$album->populate($form->getData());
$this->getEntityManager()->persist($album);
$this->getEntityManager()->flush();
// Redirect to list of albums
return $this->redirect()->toRoute('album');
}
}
return array('form' => $form);
}
public function editAction()
{
$id = (int)$this->getEvent()->getRouteMatch()->getParam('id');
if (!$id) {
return $this->redirect()->toRoute('album', array('action'=>'add'));
}
$album = $this->getEntityManager()->find('Album\Entity\Album', $id);
$form = new AlbumForm();
$form->setBindOnValidate(false);
$form->bind($album);
$form->get('submit')->setAttribute('label', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->post());
if ($form->isValid()) {
$form->bindValues();
$this->getEntityManager()->flush();
// Redirect to list of albums
return $this->redirect()->toRoute('album');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
public function deleteAction()
{
$id = (int)$this->getEvent()->getRouteMatch()->getParam('id');
if (!$id) {
return $this->redirect()->toRoute('album');
}
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->post()->get('del', 'No');
if ($del == 'Yes') {
$id = (int)$request->post()->get('id');
$album = $this->getEntityManager()->find('Album\Entity\Album', $id);
if ($album) {
$this->getEntityManager()->remove($album);
$this->getEntityManager()->flush();
}
}
// Redirect to list of albums
return $this->redirect()->toRoute('default', array(
'controller' => 'album',
'action' => 'index',
));
}
return array(
'id' => $id,
'album' => $this->getEntityManager()->find('Album\Entity\Album', $id)->getArrayCopy()
);
}
}
What am i doing wrong here, I am not able to persist any changes that i make.
Because there's no post method. Try getPost(); see here Zend\Http\Request