I am trying to update two records/rows of same table in AJAX
public function reorderApplications(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$from = $request->request->get('from');
$to = $request->request->get('to');
$em = $this->getDoctrine()->getManager();
/** #var Application $fromApplication */
$fromApplication = $em->getRepository('IndexBundle:Application')->find($from['application']);
/** #var Application $toApplication */
$toApplication = $em->getRepository('IndexBundle:Application')->find($to['application']);
try {
$fromApplication->setOrder($to['position']);
$toApplication->setOrder($from['position']);
$em->flush();
$response = array(
'response' => 'success',
'message' => 'Applications were reordered successfully.'
);
} catch (\Exception $e) {
$response = array(
'response' => 'error',
'message' => $e->getMessage()
);
}
return new JsonResponse($response, 200);
}
Eventually, try fails at $em->flush() and I get error:
An exception occurred while executing 'UPDATE application SET order =
? WHERE id = ?' with params ["3", 4]:↵↵SQLSTATE[42000]: Syntax error
or access violation: 1064 You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the right
syntax to use near 'order = '3' WHERE id = 4' at line 1
Anyone knows what could be the problem?
order is a reserved keyword in SQL.
To use it in column name, you must put backquotes in the definition:
#Column(name="`order`")
order is a reserved keyword in mysql. Try renaming the field.
http://dev.mysql.com/doc/refman/5.7/en/keywords.html
Related
I created a custom operation to send sms using symfony and sarbacane :
in my AppUser entity I added annotations :
* "GET",
* "PUT",
* "PATCH",
* "DELETE",
* "send_sms"={
* "method"="POST",
* "path"="/app_users/{id}/sms",
* "controller"=SmsController::class,
* "normalization_context"={"groups"={"user:read"}},
* "put"={"validation_groups"={"Default", "sedValidation"}}
* }
* }
In my controller I implements the invoke method :
public function __invoke(AppUser $user, Request $request, SerializerInterface $serializer) : bool
{
$data = $request->getContent();
// json decode transforms to object by default
// add true
$json_encode = json_decode($data, true);
$content = $json_encode['content'];
$currentUser = $this->getUser();
$currentUserPhone = $currentUser->getPhone();
$res = $this->sarbacaneApiHelper->call('campaigns/sms', [
'name' => sprintf("eXpanded n°%s", uniqid()),
'kind' => 'SMS_NOTIFICATION',
'smsFrom' => "eXpanded", // entre 3 et 11 caractères alpha-numériques
'content' => $content, // max 450 caractères
]);
$phone = $currentUserPhone;
$sarbacaneCampaignId = $res->id;
// Ajoute des destinataires à la campagne Sarbacane
$res = $this->sarbacaneApiHelper->call(sprintf('campaigns/%s/recipients', $sarbacaneCampaignId), [
[
'phone' => $phone,
],
]);
$params = [
"phone" => $currentUserPhone,
];
$this->sarbacaneApiHelper->call(sprintf('campaigns/%s/send', $sarbacaneCampaignId), $params);
$sent = true;
return $sent;
}
I tested the api using postman, and I got 500 internal Server Error :
"hydra:description": "Cannot validate values of type "boolean" automatically. Please provide a constraint."
Why does this error message appear?
An invoke() method must return either:
a Symfony\Component\HttpFoundation\ResponseResponse instance,
an instance of the target entity (seems to be AppUser in this case).
In your case, the method returns true; since the validation comes right after the controller, Api-Platform try to validate this boolean, and this is not possible. It expects an entity.
About the showed code within the question
It remains pretty unclear to me what you're trying to achieve:
Why the $user arg is never used?
Do you want to save any entity once your e-mail is sent?
Why do you fetch the Request content ?
I am writing a method to request a password reset in symfony
I get the email of the user from the posted value
$data = $form->getData();
$email = $data['email'];
It seems that I get the good email value and I can verify it by a
dump($email);
that returns
"firstname.name#domain.ext"
Then I try to fetch a user in the database with
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email" => $email]);
but the result is null.
After that I try 2 different ways and both of them work perfectly i.e. give a valid user.
1- I replace
$email = $data['email'];
with
$email = "firstname.name#domain.ext";
2-
I change the line that fetches the user with:
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email" => "firstname.name#domain.ext"]);
Obviously the trouble comes from the way the value is passed to the findOneBy method, not because the user is not in the database.
I would like to know what I should do to use the value I got from the Post ?
Here is my controller
/**
* #Route("/passforgotten", name="app_forgotten_password", methods="GET|POST")
*/
public function askResetPass(
Request $request,
UserPasswordEncoderInterface $encoder,
ManagerRegistry $managerRegistry,
\Swift_Mailer $mailer,
TokenGeneratorInterface $tokenGenerator
): Response {
$defaultData = ['message' => 'Type your message here'];
$form = $this->createFormBuilder($defaultData)
->add('email', EmailType::class)
->add('send', SubmitType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$email = $data['email'];
//alternative that works of course with a real email
//$email="firstname.name#domain.ext";
dump($email);
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(["email" => $email]);
dump($email);
dump($user);
if ($user === null) {
$this->addFlash('danger', 'Email Inconnu, recommence !');
return $this->redirectToRoute('app_register');
}
$token = $tokenGenerator->generateToken();
$manager = $managerRegistry->getManager();
try {
$user->setResetPasswordToken($token);
$manager->flush();
} catch (\Exception $e) {
$this->addFlash('warning', $e->getMessage());
return $this->redirectToRoute('home');
}
//this has not been tested yet
$url = $this->generateUrl('security/ask_reset_password', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
$message = (new \Swift_Message('Rénitialisation du mot de pass'))
->setFrom(array('symfony#domain.ext'))
->setTo($user->getEmail())
->setBody('hello ask for reset pass!'
);
$mailer->send($message);
$this->addFlash('notice', 'Mail correctement envoyé !');
//this is not finished
return $this->redirectToRoute('a_route');
}
return $this->render('security/ask_reset_password.html.twig', [
'form' => $form->createView()
]);
}
Sorry but I was passing a misspelled email a letter l just before a b was missing and I used the form memorization of it each time. In fact it works in every case.
i do this steps:
1.) I call my api endpoint: http://localhost:8000/api/addrole
2.) This is the controller called:
/**
* #Rest\Post("/addrole")
*/
public function addRoleAction(Request $request)
{
$userid = $request->get('userid');
$assignedRole = $request->get('role');
$assignedRoleName = $request->get('role_name');
// Obtain the User
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')
->find($userid);
// If the user gives not exists, throw error
if (!$user) {
throw new HttpException (400,"No se ha encontrado el usuario solicitado: " .$userid);
}
// obtain present user roles
$presentRoles = $user->getRoles();
$role_length = count($presentRoles);
$role_list = array();
for ($i=0; $i <$role_length ; $i++) {
array_push($role_list,$presentRoles[$i]->getRole());
}
if(!in_array($assignedRole,$role_list)){
$role = $em->getRepository('AppBundle:Role')
->findOneBy(array('role' => $assignedRole));
$user->addRole($role);
$em->persist($user); // persisting only the user.
$em->flush();
$data = array(
'result' => 'Rol asignado',
'user' => $user,
'assignedRole' => $assignedRole
);
return $data;
} else {
throw new HttpException (400,"El usuario ya posee el rol solicitado");
}
}
3.) The data on this step:
$user->addRole($role);
$em->persist($user); // persisting only the user.
$em->flush();
is saving the data on the DB.
4.) this is the response:
{
"error": {
"code": 500,
"message": "Internal Server Error",
"exception": [
{
"message": "A circular reference has been detected (configured limit: 1).",
"class": "Symfony\\Component\\Serializer\\Exception\\CircularReferenceException",...
5.) if i comment this line:
//$em->flush();
the data obviosly don't save, but the error is not throwed.
Any clue about this?
Finally i found the error.
The problem is on this code:
...
post $em->flush();
this: $data = array('result' => 'Rol asignado', 'user' => $user, 'assignedRole' => $assignedRole );
return $data;
After the flush i called the $user object. This generate the problem.
Thanks to all.
I would like to create database for user when he register. The code for database creation looks like this
$connectionFactory = $this->container->get('doctrine.dbal.connection_factory');
$connection = $connectionFactory->createConnection(array(
'driver' => 'pdo_mysql',
'user' => 'root',
'password' => 'mysecretpassword',
'host' => 'localhost',
'dbname' => 'userdatabase',
));
$params = $connection->getParams();
$name = isset($params['path']) ? $params['path'] : $params['dbname'];
unset($params['dbname']);
$tmpConnection = DriverManager::getConnection($params);
// Only quote if we don't have a path
if (!isset($params['path'])) {
$name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name);
}
$error = false;
try {
$tmpConnection->getSchemaManager()->createDatabase($name);
echo sprintf('<info>Created database for connection named <comment>%s</comment></info>', $name);
} catch (\Exception $e) {
echo sprintf('<error>Could not create database for connection named <comment>%s</comment></error>', $name);
echo sprintf('<error>%s</error>', $e->getMessage());
$error = true;
}
$tmpConnection->close();
I have entities created for that database in AccountBundle but do not know how to create database schema when user database is created.
It is often used in the tests. An example can be seen in LiipFunctionalTestBundle.
$metadatas = $om->getMetadataFactory()->getAllMetadata();
$schemaTool = new SchemaTool($om);
$schemaTool->dropDatabase($name);
if (!empty($metadatas)) {
$schemaTool->createSchema($metadatas);
}
I want do one functional test over on service Symfony2. The idea is call before to the controller and after that, load the service with the function. The function is this one:
function save($title,$description,$setId,$html,$validate,$articles){
$articles = explode(',', $articles);
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
}else{
$profileId = $this->container->get('security.context')->getToken()->getUser()->getId();
$userName = $this->container->get('security.context')->getToken()->getUser()->getUserName();
}
}
and now my test code is :
$client = static::createClient();
$crawler = $client->request('GET','/sets/save',
array(
"title"=>"rtyui",
"description"=>"aksdjhashdkjahskjdh",
"set_id"=>"",
"html"=>"",
"validate"=>1,
"articels"=>"3,4"
)
);
but doesn't work already that I have this lines:
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
Now, the question is, how i can do the validation process? I've tried to do this validation process as show the documentation:
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'username',
'PHP_AUTH_PW' => 'pa$$word',
));
but I got the same error.
Also you can login user by Security Token:
$client = static::createClient();
$container = $client->getContainer();
$container->get('security.context')->setToken(
new UsernamePasswordToken(
$user, null, 'main', $user->getRoles()
)
);
Where:
$user - instance of User entity with role ROLE_USER,
main - your security provider name