I am trying to update a single data in my entity class, but the doctrine is always returning this error
Error: Call to a member function setStats() on a non-object**
$em = $this->getDoctrine()->getManager();
$result = $em->getRepository('MyBundle:UserStats')->findBy(array('ownerPhone' => 1002));
if( isset($result) && $result !== false ) {
echo $result->setConditionState(0); // ConditionState is a boolean condition which i want to set it to false
}
$em->flush();
My entity class for conditionState---
/**
* Set conditionState
*
* #param boolean $conditionState
*
* #return UserStats
*/
public function setConditionState($conditionState)
{
$this->conditionState = $conditionState;
return $this;
}
/**
* Get conditionState
*
* #return boolean
*/
public function getConditionState()
{
return $this->conditionState;
}
Do anyone have an idea where I am making the mistake?
findBy method returns an array. Use findOneBy instead.
Related
I have two models for Island and Fisher. I want to use datatable to display island name instead of (island_id) fisher_first_name and fisher_last_name
As displayed in the datatable
Island Id Fisher First Name Fisher Last Name
1 Dovecot Imap
2 Jon Tim
These are my two models relationships
public function fishers(){
return $this->hasMany(Fisher::Class);
}
public function island(){
return $this->belongsTo(Island::Class,'island_id');
}
This is the getColumns fuction from FisherDatatable that I need to use to change the island_id to island_names
protected function getColumns()
{
return [
'island_id'
'fisher_first_name',
'fisher_last_name',
];
}
This is also an extract from a FisherDatatable to show Island and Fisher relationship
public function query(Fisher $model)
{
return $model->newQuery()->with(['island']);
}
This is my Controller
namespace App\Http\Controllers;
use App\DataTables\FisherDataTable;
use App\Http\Requests;
use App\Http\Requests\CreateFisherRequest;
use App\Http\Requests\UpdateFisherRequest;
use App\Repositories\FisherRepository;
use App\Models\Island;
use Flash;
use App\Http\Controllers\AppBaseController;
use Response;
class FisherController extends AppBaseController
{
/** #var FisherRepository */
private $fisherRepository;
public function __construct(FisherRepository $fisherRepo)
{
$this->fisherRepository = $fisherRepo;
}
/**
* Display a listing of the Fisher.
*
* #param FisherDataTable $fisherDataTable
* #return Response
*/
public function index(FisherDataTable $fisherDataTable)
{
return $fisherDataTable->render('fishers.index');
}
/**
* Show the form for creating a new Fisher.
*
* #return Response
*/
public function create()
{
$islands = Island::pluck('island_name','id');
return view('fishers.create')->with('islands',$islands);
}
/**
* Store a newly created Fisher in storage.
*
* #param CreateFisherRequest $request
*
* #return Response
*/
public function store(CreateFisherRequest $request)
{
$input = $request->all();
$fisher = $this->fisherRepository->create($input);
Flash::success('Fisher saved successfully.');
return redirect(route('fishers.index'));
}
/**
* Display the specified Fisher.
*
* #param int $id
*
* #return Response
*/
public function show($id)
{
$fisher = $this->fisherRepository->find($id);
if (empty($fisher)) {
Flash::error('Fisher not found');
return redirect(route('fishers.index'));
}
return view('fishers.show')->with('fisher', $fisher);
}
/**
* Show the form for editing the specified Fisher.
*
* #param int $id
*
* #return Response
*/
public function edit($id)
{
$fisher = $this->fisherRepository->find($id);
$islands = Island::pluck('island_name','id');
if (empty($fisher)) {
Flash::error('Fisher not found');
return redirect(route('fishers.index'));
}
return view('fishers.edit')
->with('fisher', $fisher)
-> with('islands', $islands);
}
/**
* Update the specified Fisher in storage.
*
* #param int $id
* #param UpdateFisherRequest $request
*
* #return Response
*/
public function update($id, UpdateFisherRequest $request)
{
$fisher = $this->fisherRepository->find($id);
if (empty($fisher)) {
Flash::error('Fisher not found');
return redirect(route('fishers.index'));
}
$fisher = $this->fisherRepository->update($request->all(), $id);
Flash::success('Fisher updated successfully.');
return redirect(route('fishers.index'));
}
/**
* Remove the specified Fisher from storage.
*
* #param int $id
*
* #return Response
*/
public function destroy($id)
{
$fisher = $this->fisherRepository->find($id);
if (empty($fisher)) {
Flash::error('Fisher not found');
return redirect(route('fishers.index'));
}
$this->fisherRepository->delete($id);
Flash::success('Fisher deleted successfully.');
return redirect(route('fishers.index'));
}
}
just need to add name, title and data array to your getColumns methos
protected function getColumns()
{
return [
['name'=>'dropdown_label','title'=>'new name of label','data'=>"dropdown_label"],
['name'=>'dropdown_value','title'=>'new name of dropdwon value','data'=>"dropdown_value"],
'active'
];
}
I'm new with the symfony framework. I'm trying to create webservices with FOSRest bundle but I had a problems when I tried to implement the POST method for one entity with json.
Test:
public function testJsonPostNewTesteAction(){
$this->client->request(
'POST',
'/api/teste/new',
array(),
array(),
array(
'Content-Type' => 'application/json',
'Accept' => 'application/json'
),
'{"Teste":{"title":"O teu title"}}'
);
$response = $this->client->getResponse();
$this->assertJsonResponse($response, Codes::HTTP_CREATED);
}
Controller:
/**
*
* #Config\Route(
* "/teste/new",
* name="postTestNew"
* )
* #Config\Method({"POST"})
*
* #param Request $request the request object
*
* #return View|Response
*/
public function postNewTeste(Request $request){
return $this->processFormTest($request);
}
/**
* Method for create the process form to Advertisements
*
* #param Request $request
*
* #return mixed
*/
private function processFormTest(Request $request){
$form = $this->createForm(
new TesteType(),
new Teste()
);
$form->bind($request);
//$from->handleRequest($request);
if ($form->isValid()) {
$test = $form->getData();
return $test;
}
return View::create($form, Codes::HTTP_BAD_REQUEST);
}
The problem is when I use the handleRequest(), the method isValid() returns false because the form didn't submit. So I try to change the handleRequest to the bind method. In the last case, the method isValid() returns true but the method getData() returns a null object.
I don't know if the problem is the type form class bellow.
Type Form:
/**
* The constant name to that type
*/
const TYPE_NAME = "Teste";
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options){
parent::buildForm($builder, $options);
$builder->add("title", ValidationType::TEXT);
}
/**
* {#inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(
array(
'csrf_protection' => false,
'cascade_validation' => true,
'data_class' => 'oTeuGato\DatabaseBundle\Entity\Teste'
)
);
}
/**
* Returns the name of this type.
*
* #return string The name of this type
*/
public function getName(){
return AdvertisementType::TYPE_NAME;
}
I need to POST the entity with both ways. Anyone sugest anything for my problem?
Thanks for the patience!
Got the same issue with the form binding, the only way i found to solve it was to set an empty string to the form getName function:
/**
* Returns the name of this type.
*
* #return string The name of this type
*/
public function getName(){
return '';
}
And i would suggest to use the handleRequest method when you bind your data because the bind method is deprecated:
private function processFormTest(Request $request){
$form = $this->createForm(
new TesteType(),
new Teste()
);
$from->handleRequest($request);
if ($form->isValid()) {
$test = $form->getData();
return $test;
}
return View::create($form, Codes::HTTP_BAD_REQUEST);
}
It looks more like a hack but seems like it's the only way for now:
https://github.com/FriendsOfSymfony/FOSRestBundle/issues/585
I am not entirely sure but I think it's because you're sending the data with: 'Content-Type' => 'application/json'
in stead of 'Content-Type' => 'application/x-www-form-urlencoded'
Or at least I think that's the reason why the handleRequest is not doing it's thing.
I have an entity called User which has inheritance for Student, Professional and Business.
When a user is registered, is only a User but they must update their profile and choose which kind of user is, I have a form which handles this, a controller which gets the form data, but I can't update the discriminator field type with $userEntity->setType()
This is my mapping stuff
class User
{
const TYPE_BASIC = "Basico";
const TYPE_STUDENT = "Estudiante";
const TYPE_PROFESSIONAL = "Profesional";
const TYPE_BUSINESS = "Empresa";
protected $type = self::TYPE_BASIC;
public function getType()
{
return self::TYPE_BASIC;
}
public function setType($type)
{
$this->type = $type;
}
class Student extends User
{
protected $type = self::TYPE_STUDENT;
And then Professional and Business just like Student (changing const)
<entity name="User" table="user_base" inheritance-type="JOINED">
<discriminator-column name="type" type="string"/>
<discriminator-map>
<discriminator-mapping value="Basico" class="User"/>
<discriminator-mapping value="Estudiante" class="Student"/>
<discriminator-mapping value="Profesional" class="Professional"/>
<discriminator-mapping value="Empresa" class="Business"/>
</discriminator-map>
the child tables are named user_xxx where xxx = Student/Professional/Business
And this is my controller
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$data = $form->all();
$type = $data['type']->getData();
$email = $data['email']->getData();
$profile = $data['profile']->all();
$name = $profile['name']->getData();
$lastName = $profile['lastName']->getData();
$birth = $profile['birth']->getData();
$profileEntity = new Profile();
$profileEntity->setBirth($birth);
$profileEntity->setName($name);
$profileEntity->setLastName($lastName);
$profileEntity->setUser($user);
$em->persist($profileEntity);
ladybug_dump($type);
$userEntity = $em->getRepository('User')->find($user);
$userEntity->setProfile($profileEntity);
$userEntity->setType($type);
if($user->getEmail() != $email)
$userEntity->setEmail($email);
$em->persist($userEntity);
$em->flush();
}
Everything is persisted but type field, which remains it's original data. I know when I change discriminator column I need to create a new row inside it's child element, but first I want to know how to change the discriminator column.
it is possible if you use this custom bit of code in the Form of a Trait which you can use inside a Repository.
The Trait:
namespace App\Doctrine\Repository;
use App\Exception\InvalidDiscriminatorClassException;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DBALException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;
/**
* Discriminator Trait
*/
trait DiscriminatorTrait
{
/**
* #return ClassMetadata
*/
abstract public function getClassMetadata();
/**
* #return EntityManager
*/
abstract public function getEntityManager();
/**
* Update Discriminator Column
*
* #param integer $id
* #param string $class
* #return boolean
* #throws InvalidDiscriminatorClassException
*/
private function updateDiscriminatorColumn($id, $class)
{
/* #var ClassMetadata $classMetadata */
$classMetadata = $this->getClassMetadata();
if (!in_array($class, $classMetadata->discriminatorMap)) {
throw new InvalidDiscriminatorClassException($class);
}
$identifier = $classMetadata->fieldMappings[$classMetadata->identifier[0]]["columnName"];
$column = $classMetadata->discriminatorColumn["fieldName"];
$value = array_search($class, $classMetadata->discriminatorMap);
/* #var Connection $connection */
$connection = $this->getEntityManager()->getConnection();
try {
$connection->update(
$classMetadata->table["name"],
[$column => $value],
[$identifier => $id]
);
}
catch (DBALException $e) {
return false;
}
return true;
}
}
According to the Doctrine documentation on Inheritance mapping, it is not possible to either get or set the type. You may wish take advantage of PUGXMultiUserBundle, which readily handles the mapping. This bundle also makes it possible for your users to register with the appropriate profile.
I am planning to make a reverse geocoding based on the BazingaGeocoderBundle. A simple way to do that is write this simple code in the controller:
$result = $this->container
->get('bazinga_geocoder.geocoder')
->using('google_maps')
->reverse(48.79084170157100,2.42479377175290);
return $this->render("MinnAdsBundle:Motors:test.html.twig",
array('result'=>var_dump($result)));
Until here, things are going well.
My objective is to make the code nicer & resuable. So, I used this article to write my own GeocoderEventSubscriber as describer below:
<?php
namespace Minn\AdsBundle\Doctrine\Event;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Event\LifecycleEventArgs;
//use Geocoder\Provider\ProviderInterface;
use Bazinga\Bundle\GeocoderBundle\Geocoder\LoggableGeocoder;
/**
* Subscribes to Doctrine prePersist and preUpdate to update an
* the address components of a MotorsAds entity
*
* #author majallouli
*/
class MotorsAdsGeocoderEventSubscriber implements EventSubscriber {
protected $geocoder;
public function __construct(LoggableGeocoder $geocoder){
$this->geocoder = $geocoder;
}
/**
* Specifies the list of events to listen
*
* #return array
*/
public function getSubscribedEvents(){
return array(
'prePersist',
'preUpdate',
);
}
/**
* Sets a new MotorsAds's address components if not present
*
* #param LifecycleEventArgs $eventArgs
*/
public function prePersist(LifecycleEventArgs $eventArgs){
$motorsAds = $eventArgs->getEntity();
if($motorsAds instanceof \Minn\AdsBundle\Entity\MotorsAds){
if( !$motorsAds->getCountry()){
$em = $eventArgs->getEntityManager();
$this->geocodeMotorsAds($motorsAds,$em);
}
}
}
/**
* Sets an updating MotorsAds's address components if not present
* or any part of address updated
*
* #param PreUpdateEventArgs $eventArgs
*/
public function preUpdate(PreUpdateEventArgs $eventArgs){
$motorsAds = $eventArgs->getEntity();
if($motorsAds instanceof \Minn\AdsBundle\Entity\MotorsAds){
if( !$motorsAds->getCountry() ){
$em = $eventArgs->getEntityManager();
$this->geocodeMotorsAds($motorsAds,$em);
$uow = $em->getUnitOfWork();
$meta = $em->getClassMetadata(get_class($motorsAds));
$uow->recomputeSingleEntityChangeSet($meta, $motorsAds);
}
}
}
/**
* Geocode and set the MotorsAds's address components
*
* #param type $motorsAds
*/
private function geocodeMotorsAds($motorsAds,$em){
$result = $this->geocode
->using('google_maps')
->reverse($motorsAds->getLat(),$motorsAds->getLng());
$motorsAds->setCountry(
$em->getRepository("MinnAdsBundle:Country")->findCountryCode($result['countryCode']));
}
}
After that, I declared my EventSubscriber as a service:
services:
# ...
geocoder_motorsads.listener:
class: Minn\AdsBundle\Doctrine\Event\MotorsAdsGeocoderEventSubscriber
arguments: [#bazinga_geocoder.geocoder] # almost sure that the error is here!!
tags:
- { name: doctrine.event_subscriber }
Actually, I get this error:
ContextErrorException: Notice: Undefined property: Minn\AdsBundle\Doctrine\Event\MotorsAdsGeocoderEventSubscriber::$geocode in /home/amine/NetBeansProjects/tuto/src/Minn/AdsBundle/Doctrine/Event/MotorsAdsGeocoderEventSubscriber.php line 78
I am almost sure that error is in the declaration of arguments of the EventSubscriber. Is it #bazinga_geocoder.geocoder?
Thank you for your help!
Your property is $this->geocoder but you're calling $this->geocode, you're spelling it wrong.
I'm getting data from my accounting program in Windows Platform to my PHP Script. I'm transferring data from mssql to mysql. I decided to use PDO. I have a problem with transition. How can i supply two connection simultaneously ?
Here is my own PDO Class.
class Database {
protected $_host = "***********";
protected $_engine = "mysql";
protected $_dbuser = "***********";
protected $_dbpassword = "***********";
protected $_db = "***********";
protected $_sql;
protected $pdo;
/* #desc This Function is Setting SQL Connection
* #return SQL Connection
*
*/
protected function getPdo()
{
if ($this->pdo === NULL) {
try {
$dsn = $this->_engine.':dbname='.$this->_db.';host='.$this->_host.';charset=utf8';
$this->pdo = new PDO($dsn, $this->_dbuser, $this->_dbpassword, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
));
//$this->pdo->setAttribute();
//$this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
return $this->pdo;
}
/* #desc This Function is Preparing Sql Statement For Query
* #return array Returns PDO Object Query
*
*/
public function query($sql)
{
return $this->_sql = $this->getPdo()->prepare($sql);
}
/* #desc This Function is for Binding Values into SQL Statements
* #return Binded SQL Statements
*
*/
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->_sql->bindValue($param, $value, $type);
}
/* #desc This Function Execute Query
* #return SQL Execution
*
*/
public function execute($values = NULL){
return (!isset($values)) ? $this->_sql->execute() : $this->_sql->execute($values);
}
/* #desc This Function Execute Query and Fetch Multiple Result
* #return array Returns Array of Table Rows. Array is multidimensional
*
*/
public function queryResults(){
$this->execute();
return $this->_sql->fetchAll(PDO::FETCH_ASSOC);
}
/* #desc This Function Execute Query and Fetch Only Single Result
* #return array Returns Array of Table Row. Array is not multidimensional.
*
*/
public function queryResult(){
$this->execute();
return $this->_sql->fetch(PDO::FETCH_ASSOC);
}
public function queryColumn($index = NULL){
$index = (isset($index)) ? intval($index) : 0;
$this->execute();
return $this->_sql->fetchAll(PDO::FETCH_COLUMN,$index);
// $this->execute();
// return $this->_sql->fetchAll(PDO::FETCH_COLUMN);
}
/* #desc This Function Returns Effected Row Count during Update, Delete and Insert
* #return int Returns Effected Row Count
*
*/
public function effected(){
return $this->_sql->rowCount();
}
/* #desc This Function Returns Effected Row Count during Update, Delete and Insert
* #return int Returns Effected Row Count
*
*/
public function rowCount(){
return count($this->queryResults());
}
public function lastID(){
return $this->_sql->lastInsertId();
}
You need to create 2 instances of PDO class - one for MSSQL and one for MySQL.