I've got a problem with my code. I am just trying to insert a simple set of data to my db, but doctrine insert my attribute (telVerifCode) as NULL.
I've dumped my data and figured out, that attribute (telVerifCode) has some value in it, but after I flush it is set to NULL.
This is my controller:
$user = $this->getUser();
if ($user->getTel() != $tel || $user->getTelCode() != $telCode) {
try {
$code = $this->sendTelehopneCode($user);
} catch (\Exception $e) {
//.......
}
// update user phone verifcation fields //
$user->setTelVerifCode($code);
$user->setLastTelVerificationCodeDate(new \DateTime());
$em->persist($user);
$em->flush();
}
My ORM Mapping:
/**
* #var string
*
* #ORM\Column(name="tel_verification_code", type="string", length=255, nullable=true)
*/
protected $telVerifCode;
/**
* #var \DateTime
*
* #ORM\Column(name="last_tel_verification_code_date", type="date", nullable=true)
*/
protected $lastTelVerificationCodeDate;
sendTelehopneCode function :
private function sendTelehopneCode($user)
{
$code = strval(rand(100000, 999999));
$tel = $user->getTelCode() . $user->getTel();
$msg = 'code:' . $code;
$twilio = $this->get('twilio.api');
try {
$message = $twilio->account->messages->sendMessage(
"+14*******", // Verified Outgoing Caller ID or Twilio number
$tel, // The phone number you wish to send a message to
$msg
);
} catch (\Services_Twilio_RestException $e) {
throw $e;
}
return $code;
}
Try clearing your doctrine caches, the code looks fine and cannot be the issue.
./bin/console doctrine:cache:clear-metadata
./bin/console doctrine:cache:clear-query
./bin/console doctrine:cache:clear-result
I solved the problem, I made a listener On preUpdate one that puts the value null, I completely forgotten it :(
Maybe your problem is due to a typo in your setter.
Are you sure your setter setTelVerifCode looks exactly like this?
public function setTelVerifCode($code)
{
$this->telVerifCode = $code;
}
Related
i have a error in my data and i get error out of range on a integer column and i try to prevent closed entity manager for proceeding work and for this purpose i reset manager in exception
public function renewDeliveryTime($delayReport) : void
{
try {
$this->delayReportRepository->updateRenewedDeliveryTimeAt($delayReport, 50000000);
}catch (\Exception $exception){
// out of range error
$this->managerRegistry->resetManager();
}
}
public function updateRenewedDeliveryTimeAt($delayReport,$delayDuration)
{
/**
* #var DelayReport $delayReport
*/
$delayReport->setDelayDuration($delayDuration);
$delayReport->setStatus(DelayReport::STATUS['DONE']);
$this->getEntityManager()->flush();
}
the problem is after i have another object and almost same operation in database but seems $this->getEntityManager()->flush() not work any more and nothing happens in database . it is related to $this->managerRegistry->resetManager()
public function enqueue($delayReport) : void
{
$this->pushInQueueReport($delayReport);
$this->delayReportRepository->updateStatus($delayReport, DelayReport::STATUS['IN_QUEUE']);
}
public function updateStatus($delayReport, $status)
{
/**
* #var DelayReport $delayReport
*/
$delayReport->setStatus($status);
$this->getEntityManager()->flush();
}
what is the problem and solution for this?
The problem with resetManager() is, that not all services wich has a reference to the entitymanager directly will be magically updated to have the new instance.
In updateStatus() Method you can easy check if your entity is Managed by the entity manager.
$uow = $this->getEntityManager()->getUnitOfWork();
if($uow->getEntityState($delayReport) !== UnitOfWork::STATE_MANAGED) {
// not managed
}
Dont know if a reassign can help here like $this->getEntityManager()->merge($delayReport).
BUT its really better to avoid a closed manager and validate your data before.
EDIT:
Not testet, if you will get the resetted EntityManager over the Registry. But its worth a try.
$entityManager = $managerRegistry->getManagerForClass(get_class($delayReport));
I'm using longman/telegram-bot package at my Yii2 project.
class GenericmessageCommand extends SystemCommand
{
/**
* #var string
*/
protected $name = 'genericmessage';
/**
* #var string
*/
protected $description = 'Handle generic message';
/**
* #var string
*/
protected $version = '1.0.0';
/**
* Main command execution
*
* #return ServerResponse
*/
public function execute(): ServerResponse
{
$message = $this->getMessage();
if (in_array($message->getType(), ['audio', 'document', 'photo', 'video', 'voice'])) {
$doc = call_user_func([$message, 'get' . $message->getType()]);
($message->getType() === 'photo') && $doc = end($doc);
$photoId = $doc->file_id;
$download_path = $this->telegram->getDownloadPath();
$file = Request::getFile(['file_id' => $photoId]);
if ($file->isOk() && Request::downloadFile($file->getResult())) {
return $this->replyToChat(' file is located at: ' . $download_path . '/' . $file->getResult()->getFilePath());
} else {
return $this->replyToChat('Failed to download.');
}
}
}
}
Just like that
It working fine when I'm using getUpdates method https://github.com/php-telegram-bot/core#getupdates-installation
But it doesn't work when I use WebHooks. Even though I get the same answer from my bot... It says "Ok" and "file is located at...", but there is no such file.
that because of webhook using backend of Yii2 advanced.... it stores all files at backend (because my webhook looking on backend), but i searching them at frontend (bacause i'm stupid).
It's my first time to use Laravel and Redis. I understand how to get, set, etc of Redis on Terminal. But no idea how to apply Redis on Laravel application.
I have application that saves participant's information in DB with MVC pattern. and I'd like to change it to use Redis cache to make it faster(and for practice). What do I have to do? Could you explain it with code?
This is ParticipantController. 'edit' function send user to edit page, and user edit the information and push 'save', it activate 'update' function. store/updateUserInput functions are just saving data to DB nothing else.
/**
* Show the form for editing the specified participant.
*
* #param int $id
* #return View
*/
public function edit(int $id): View
{
$participant = Participant::find($id);
if(empty($participant)){
return view('errors.404');
}
return view('participants.edit', ['participant'=>$participant]);
}
/**
* Update the specified participant in storage.
*
* #param ParticipantValidation $request
* #return RedirectResponse
*/
public function update(ParticipantValidation $request): RedirectResponse
{
$participant = Participant::find($request->id);
if(empty($participant)){
return view('errors.404');
}
$detail = $request->all();
Participant::updateUserInput($detail);
return redirect()->route('participants.create', $detail['event_id'])->with('success', 'Updated!');
}
+plus I tried this code on top of 'Controller' to use sth like $redis->set('message', 'Hello world'); but there's error that they cannot find 'Predis/Autoload.php'
require 'Predis/Autoload.php';
PredisAutoloader::register();
try {
$redis = new PredisClient();
}
catch (Exception $e) {
die($e->getMessage());
}
You can use the Cache facade
In your .env file, you must add CACHE_DRIVER=redis
Then whenever you want to get an instance of Participant:
$participant = null;
$key ="Participant".$id;
if(Cache::has($key)//get participant from cache
$participant = Cache::get($key);
else{//get participant and cache for 3 minutes
$participant = Participant::find($id);
$seconds = 180;
Cache::set($key, $participant, $seconds);
}
I want to create new Entity SlideTranslation, and assign existed slide.
But every time entity had created without id of Slide. I can create SlideTranslation and than assign Slide to it, but it seems bad solution for me.
$slide = $em->getRepository('Model:Slide')->find($id);
if(isset($slide)) {
try {
$slideTranslation = new SlideTranslation();
$slideTranslation->setTranstable($slide);
$slideTranslation->setLocale('uk');
$slideTranslation->setAltText('Alt text');
$em->persist($slideTranslation);
$em->flush();
} catch (Exception $e) {
dump($e->getMessage());
}
}
Relations.
/**
* #ORM\ManyToOne(targetEntity="Model\Entity\Slide", inversedBy="tranlations")
* #ORM\JoinColumn(name="translatable_id", referencedColumnName="id")
*/
private $transtable;
I have tried method with getReference, but no result. Maybe I am breaking some patterns or principles and It's not possible in Doctrine2.
You will have to probably do it in the other way around
$slide = $em->getRepository('Model:Slide')->find($id);
$slideTranslation = new SlideTranslation();
$slideTranslation->setLocale('uk');
$slideTranslation->setAltText('Alt text');
$slide->addTranslation($slideTranslation);
$em->flush();
Then add cascade to the Slide entity, and you don't even need to persist the entity Translation
/**
* #ORM\OneToMany(targetEntity="Model\Entity\SlideTranslation", mappedBy="transtable", cascade={"persist", "remove"})
*/
private $translations;
So I've this relations defined in my entities:
class Producto
{
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Norma", inversedBy="normasProducto", cascade={"persist"})
* #ORM\JoinTable(name="nomencladores.norma_producto", schema="nomencladores",
* joinColumns={#ORM\JoinColumn(name="producto_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="norma_id", referencedColumnName="id")}
* )
*/
protected $productoNormas;
}
class Norma
{
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Producto", mappedBy="productoNormas", cascade={"persist"})
*/
protected $normasProducto;
}
And I'm trying to check if a given pair producto_id-norma_id already exists for not try to insert it once again and I'm doing as follow:
$exists = $em->getRepository('AppBundle:Producto')->findOneByProductoNormas($productoId);
if ($exists) {
$status = 400;
} else {
try {
$producto->addProductoNormas($normaEntity);
$em->flush();
$response['success'] = true;
} catch (Exception $ex) {
$status = 400;
$response['error'] = $ex->getMessage();
}
}
But I'm getting this error:
Notice: Undefined index: joinColumns in
/var/www/html/project.dev/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php
line 1665
Doing a research on Google and here on SO I found that possible it's a bug as point here or perhaps is not and we (me and the others who report the issue) are doing something wrong. I can't find where the issue or problem is so any advice or help will be fine for me and others. The only idea I have in mind is create a view at RDBMS and then create a entity for read it and check if record already exists, I have not other than this one, any ideas? Help? Working example code?
Actually you can use 'database_connection' service to check if such row exists:
$this->get('database_connection')
->fetchColumn('select count(id) as cnt
from <norma_producto_table>
where producto_id = ? and
norma_id = ?', array($producto_id, $norma_id));
That's really easier than trying to handle this with many to many relations methods. I would do that if I had to do what you need (and actually I'm doing so).
I don't know the definitive answer but i had the same problem and it had something to do with my entities annotations can't tell you exactly what though..
Here is a working example with photos and albums
class Photo
{
/**
* #ORM\ManyToMany(targetEntity="Acme\MyBundle\Entity\Album", inversedBy="photos")
* #ORM\JoinColumn(nullable=true)
*/
private $albums;
class Album
{
/**
* #ORM\ManyToMany(targetEntity="Acme\MyBundle\Entity\Photo", mappedBy="albums")
* #ORM\JoinColumn(nullable=true)
*/
private $photos;
In order to check the existence you could do, let's say you're searching for an idPic photo
$photo = $repository ... ->findOneBy($idPic)
if($photo->getAlbums()->contains($album))