$options['class'] = 'App\\Entity\\Data';
$options['attr'] = array('class' => 'form-control select2');
$options['query_builder'] = function (EntityRepository $er) use ($fieldId,$documentId) {
return $er->createQueryBuilder('data')
->leftJoin('data.documents', 'dd')
->andWhere('dd.pages = :id')
->andWhere('dd.uuid = data.document_id')
->andWhere('data.field = :field')
->setParameter(':id', 16)
->setParameter(':field', 35)
;
};
$options['choice_label'] = 'content';
The error message:
[Semantical Error] line 0, col 127 near 'field = :fie': Error: Class
App\Entity\Data has no field or association named field
Do you have the following in your class?
use Doctrine\ORM\Mapping as ORM;
class Data
{
/**
* #ORM\Column(name="field")
*/
private $field;
}
Normally that would be enough for doctrine to resolve that error
And as #yceruto says in the comments
It is
// This is right
->setParameter('field', 22)
Instead of
// This is wrong
->setParameter(':field', ...)
Related
I am beginner in Laravel 7, I am using two tables 'empmast' and 'empatten'. I displayed the values of empmast (empid, empname) and joined two fields (empstatus, doa) with same. Then I tried to push these values to 'empatten' table. The thing is these values are trying to save in the empmast instaed empatten table. Kindly assist.
Complete Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'empstatus' in 'field list'
(SQL: insert into `empmast` (`empid`, `empname`, `empstatus`, `doa`, `updated_at`, `created_at`) values (2, Kirupa Shankar, Present, 17-05-2020, 2020-05-17 06:34:26, 2020-05-17 06:34:26))
EmpAttenController:
use App\Empatten;
use App\Empmast;
use Illuminate\Http\Request;
class EmpAttenController extends Controller
{
public function store(Request $request, Empatten $empatten)
{
$member1 = $request->input('empid');
$member2 = $request->input('empname');
$member3 = $request->input('empstatus');
$member4 = $request->input('doa');
for ($i = 0; $i < count($member1); $i++) {
$empatten->empid = $member1[$i];
$empatten->empname = $member2[$i];
$empatten->empstatus = $member3[$i];
$empatten->doa = $member4;
$empatten->save();
}
}
}
Empatten(Model):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Empatten extends Model
{
protected $fillable = [
'empid' => 'array',
'empname' => 'array',
'empstatus' => 'array',
'doa'
];
}
Create new instance of your model before you try to save
use App\Empatten;
use App\Empmast;
use Illuminate\Http\Request;
class EmpAttenController extends Controller
{
public function store(Request $request)
{
$member1 = $request->input('empid');
$member2 = $request->input('empname');
$member3 = $request->input('empstatus');
$member4 = $request->input('doa');
for ($i = 0; $i < count($member1); $i++) {
$empatten = new Empatten(); // initiate your model class
$empatten->empid = $member1[$i];
$empatten->empname = $member2[$i];
$empatten->empstatus = $member3[$i];
$empatten->doa = $member4;
$empatten->save();
}
}
}
this is a newbie question, but I can't find the answer anywhere.
I am trying return a JSON response from a controller in Symfony 3.4.
In the controller I have:
namespace MegBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use MegBundle\Entity\message;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Inflector\Inflector;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class MegController extends Controller
{
/**
* #Route("/message/board/page/{page}", name = "message_board", defaults = {"page" = 1}, requirements = {"page" = "\d+"})
* #Method("GET")
*/
public function showMeg(Request $request, $page)
{
$entityManager = $this->getDoctrine()->getEntityManager();
if ($request->query->get("DESC") != null) {
$orderById = "DESC=ID";
$orderby = 'DESC';
}
if ($request->query->get("DESC") == null) {
$orderById = "ASC=ID";
$orderby = 'ASC';
}
$per = 5;
$start = ($page-1)*$per;
$query = $entityManager->createQueryBuilder()
->select("r")
->from("MegBundle:message", "r")
->orderBy('r.id', $orderby)
->setFirstResult($start)
->setMaxResults($per);
$data = $query->getQuery()->getArrayResult();
$paginator = new Paginator($query, $fetchJoinCollection = false);
$count = count($paginator);
$pages = ceil($count/$per);
return new JsonResponse(['result' => 'ok', 'ret' => ['name' => $data->getName(),
'mes' => $data->getMes(),
'update_time' => $data->getUpdateTime()->format('Y-m-d H:i:s')]]);
}
But I get
Call to a member function getName() on array.
I hope i can get JosnResponse like this
{"result":"ok","ret":{"name":[{"name":"AAA","mes":"1234","update_time":"2019-09-20 10:54:50"},{"name":"AAA","mes":"1234","update_time":"2019-09-20 11:08:53"},{"name":"Lai","mes":"AppleAppleappleAPPLE","update_time":"2019-09-20 11:11:09"}]}
Your $data is an array of data, (see $query->getQuery()->getArrayResult() )
So your are trying to get attributes from an array instead of accessing them from the appropriate object.
Since you are already getting an array result and you want to put this in the name part of your json, you could just change your jsonResponse to :
return new JsonResponse(['result' => 'ok', 'ret' => ['name' => $data]]);
You may need to change your query to specify which attributes to get and not get the whole entity, in your case name, mes and update_time.
Something like :
$entityManager->createQueryBuilder()
->select("r.name, r.mes, r.update_time")
//...
I am working in Symfony - When I am performing an action to delete a user I am receiving the following error messages:
[Semantical Error] line 0, col 7 near 'WHERE u.id =': Error: Class 'WHERE' is not defined.
500 Internal Server Error - QueryException
1 linked Exception:
QueryException »
1/2 QueryException: DELETE WHERE u.id = :id
2/2 QueryException: [Semantical Error] line 0, col 7 near 'WHERE u.id =': Error: Class 'WHERE' is not defined.
Admin Controller
/**
* #Route("/admin/user/delete/{id}", name="admin_user_delete")
* #Template
*/
public function deleteAction($id)
{
$dispatcher = $this->container->get('event_dispatcher');
$this->get('users')->delete($id);
// create the user event and dispatch it
$event = new UserEvent($id);
$dispatcher->dispatch(UserEvents::USER_DELETED, $event);
$this->get('session')->getFlashBag()->add('notice-success', 'User deleted successfully.');
return $this->redirect($this->generateUrl('admin_user_list'));
}
User.php Service
public function delete($id)
{
$this->repository->delete($id);
}
User Repository
public function delete($id)
{
$qb = $this->getEntityManager()->createQueryBuilder('u');
$qb->delete()
->andWhere($qb->expr()->eq('u.id', ':id'))
->setParameter(':id', $id)
->getQuery()
->getResult();
}
Method to delete a user with the query builder
public function delete($id)
{
$qb = $this->getEntityManager()->createQueryBuilder();
return $qb->delete('Bundle:User', 'u')
->where('u.id = :id'))
->setParameter('id', $id)
->getQuery()
->getResult();
}
How to delete a user using the built in ORM
public function delete($id) {
// get access to the entity manager
$em = $this->getEntityManager();
// get the user from the repository by id
// previous version, slightly slower as it executes a query
// $user = $em->getRepository('Bundle:User')->find($id);
// Cerads method I just found out about myself, even better version!
// this doesn't execute a query but gets a reference to the user object
// and sets the id
$user = $em->getReference('Bundle:User', $id);
// use built in methods to delete the user
$em->remove($user);
// update the database with the change
$em->flush();
}
As Jared Farrish said above, you don't need the colon in the setParameter call.
Should be:
->setParameter('id', $id)
I have a MongoDB connection & MySQL Connection details setup in my config/database.php file. I can connect to the MongoDB Details and get a response but when i try connect to the MySQL database, i get the following error:
FatalThrowableError in Builder.php line 1514:
Call to a member function compileSelect() on null
I've tried the solutions from this page:
Issue with Out of the box Laravel Authentication but none of the solutions have worked.
I'm not using any authentication on the app, just querying a MySQL database to return data.
[Updated]
Route link from app/Http/routes.php
Route::get('v1/{showdata}/{name}', 'ShowDataController#percentData');
Controller: ShowDataController.php
namespace App\Http\Controllers;
use App\ShowData;
use App\MongoDataPull;
class ShowDataController extends BaseController
{
public function percentData($showdata, $name)
{
$showdata;
$name;
$signupsremaining = 0;
//Percentage Calculator
if ((ShowData::where('name', '=', $name)->first()) === null) {
// If not found, change status to Not Listed
$percentagetakeup = 'Not Listed';
} else {
// If found, Run Percentage Calculator
$totalrequired = ShowData::select('total_required')->where('name', '=', $name)->value('total_required');
$currentinterest = ShowData::select('current_interest')->where('name', '=', $name)->value('current_interest');
$percentagetakeup = round((($currentinterest) / $totalrequired) * 100);
// Calcualte the number of signups remaining for the fibrehood.
$signupsremaining = $totalrequired - ($currentinterest);
if ($signupsremaining < 0) {
$signupsremaining = 0;
} else {
$signupsremaining = $signupsremaining;
}
}
return ['percentagetakeup' => $percentagetakeup, 'signupsremaining' => $signupsremaining];
}
}
From ShowData Model ShowData.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ShowData extends Model
{
protected $table='qualify';
protected $fillable=[
'id',
'name',
'total_required',
'current_interest',
'status'
];
}
I wrote a function in BudgetRepository that is called when inserting new data into Budget table. The function is:
public function addBudgetToClient($clientId, $budgetId)
{
return $this->createQueryBuilder('b')
->update('PanelBundle:Client', 'c')
->set('c.budget', $budgetId)
->where('c.id = ' . $clientId)
->getQuery()
->execute();
}
And the BudgetController does this:
public function addAction(Request $request)
{
$form = $this->createForm(new BudgetType());
$manager = $this->getDoctrine()->getManager();
$Budget = $manager->getRepository('PanelBundle:Budget');
$Client = $manager->getRepository('PanelBundle:Client');
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$manager->persist($form->getData());
$manager->flush();
// Here's the method:
$Budget->addBudgetToClient($form['client_id']->getData()->getId(), $Budget->getLastId());
//
$this->addFlash('success', 'Novo orçamento adicionado');
return $this->redirect($this->generateUrl('panel_budgets'));
}
}
return $this->render('PanelBundle:Budget:add.html.twig', array(
'clients' => $Client->findAll(),
'form' => $form->createView()
));
}
I tested both outputs, the getLastId is also a custom function I wrote to retrieve the biggest ID from Budget, and the $form['client_id']->getData()->getId() also retrieves the Client id. I guess Symfony2 automatically does something because Budget and Client are related, and even saving the Client id, in the database shows the Client name, I don't understand how actually.
The issue here are these errors:
[Semantical Error] line 0, col 34 near 'budget = 4 WHERE': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.
[2/2] QueryException: [Semantical Error] line 0, col 34 near 'budget = 4 WHERE': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected. +
[1/2] QueryException: UPDATE PanelBundle:Client c SET c.budget = 4 WHERE c.id = 1 +
I found many problems about this exception but they haven't had it with update function, only select.
You should not build an update query for this case using a queryBuilder. Use OOP approach to update your entities.
if ($form->isValid()) {
$budgetEntity = $form->getData();
$manager->persist($budgetEntity);
$clientEntity = $Budget->find($form['client_id']->getData()->getId());
$clientEntity->setBudget($budgetEntity);
$manager->flush();
$this->addFlash('success', 'Novo orçamento adicionado');
return $this->redirect($this->generateUrl('panel_budgets'));
}