Appear old information already entered in a form - symfony

I'm trying to show errors validation message with the old The information already entered , but the problém when the form is not valid and it's submitted else if ($form->isSubmitted()&& !$form->isValid()) : the old input content(old The information already entered) will disappear .
By the way i want after avery submition that the url end with #contact that's why i worked with this->redirect .
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$task = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($task);
$em->flush();
$this->get('session')->getFlashBag()->add(
'notice',
'Votre message est bien envoyé !'
);
} else if ($form->isSubmitted() && !$form->isValid()) {
$errors = array();
foreach ($form->all() as $key => $child) {
if (!$child->isValid()) {
foreach ($child->getErrors() as $error) {
$errors[$key] = $error->getMessage();
}
}
}
foreach ($errors as $key => $value) {
$this->get('session')->getFlashBag()->add('error', $value);
}
return $this->redirect($this->generateUrl('index') . '?a#contact');
}
return $this->render('front/index.html.twig', array('form' => $form ->createView()));
}

You should only redirect to your index if the form is valid. Right now that redirect is occurring in } else if ($form->isSubmitted() && !$form->isValid()) {, which means a redirect will occur with invalid data.
Try:
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$task = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($task);
$em->flush();
$this->get('session')->getFlashBag()->add(
'notice',
'Votre message est bien envoyé !'
);
return $this->redirect($this->generateUrl('index') . '?a#contact');
} else if ($form->isSubmitted() && !$form->isValid()) {
$errors = array();
foreach ($form->all() as $key => $child) {
if (!$child->isValid()) {
foreach ($child->getErrors() as $error) {
$errors[$key] = $error->getMessage();
}
}
}
foreach ($errors as $key => $value) {
$this->get('session')->getFlashBag()->add('error', $value);
}
}
return $this->render('front/index.html.twig', array('form' => $form ->createView()));
}
This way, if your form is not valid, it will return the render form again (with your errors included). You can see an example of a controller that follows that flow here.

Related

Incorrect password encryption

I have a small password encryption problem ^^
in my database the passwords are present, and have to present, in this form:
VwBybV5ATQ9RkdvvVZNOlldEEDU9tDjttju7t8l+HeVe4nskHeMpbuCoQsqqORUQKZ1pg7gGtFocpkSIw8N9kA==
and right now I have a function that needs to generate a password for me. Unfortunately the encryption is not good, because that's what I get:
YmY1NzFkM2VkODYwOGQ1OWFlMTRiZDVkOTc3ZDFkNzQ0ODIzN2U5NWMzNzU0ZjI1Y2U4MTZhYzBiYmExYWJjZTg2Y2JjNzYyM2QwYTJmMDUwYWJiMzQxMjliYjBjYWQxMGZiMzliYzk3OGQwZjYxMGU3Y2E0NjE0ZTkxYzFiYmM=
my code :
public function lostpasswordAction(Request $request)
{
$success = '';
$string = '';
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
$max = strlen($characters) - 1;
for ($i = 0; $i < 12; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
if ($request->request->get('email') !== null) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ApplicationSonataUserBundle:User')->findByEmail($request->request->get('email'));
if (is_null($user)) {
$response = new JsonResponse('Not Found');
$response->setStatusCode(Response::HTTP_NOT_FOUND);
return $response;
}
$login = $user[0]->getEmail();
$password = $string;
$user[0]->setPassword(hash('sha512',$password));
$em->persist($user[0]);
$em->flush();
$message = \Swift_Message::newInstance()
->setSubject('Subject')
->setFrom('no-reply#noreply.com')
->setTo($request->request->get('email'))
->setBody(
$this->renderView(
'emails/lostpassword.txt.twig',
array(
'login' => $login,
'password' => $password
)
),
'text/plain'
);
$return = $this->get('mailer')->send($message);
$success = 'Email sent';
return new JsonResponse($success);
}
$response = new JsonResponse('POST only');
$response->setStatusCode(Response::HTTP_BAD_REQUEST);
return $response;
}
Can someone help me so I get the right shape please?
Thank you in advance

Use delete_user_meta

I want to delete my usermeta in table database but give nothing. it give me an error because its not array expected string parameter
function remove_meta(){
$role = 'client'; //Select user role
$users = get_users('role='.$role);
global $wpdb;
$stats = $wpdb->get_results("
SELECT ".$wpdb->prefix." group_clients.client_id
FROM ".$wpdb->prefix." group_clients
WHERE ".$wpdb->prefix." group_clients.group_id IN (1, 2, 5, 6)
", $users); // Fetch data by selective group ID
$stats = array();
if (is_array($stats) || is_object($stats)){
//foreach ((array) $stats as $stat){
foreach ($stats as $stat) {
delete_user_meta($stat->ID, 'terms_and_conditions');
}
echo 'Fini!';
}
}
Try below code you are doing confusing code. Do not do sql query unless it is really required.
$args = array(
'role' => 'customer', //client or whatever you required
);
//geting all user
$users = get_users( $args );
foreach ($users as $result)
{
//each user id
$userId = $result->ID;
if($userId != '')
{
//getting all user meta of particular user
$all_meta_for_user = get_user_meta( $userId );
if(is_array($all_meta_for_user))
{
foreach ($all_meta_for_user as $key => $value) {
$terms =get_user_meta($userid,'terms_and_conditions',true);
if($terms !=''){
delete_user_meta($userId, 'terms_and_conditions');
}
}
}
}
}
with hook
add_action('init','deletedata');
function deletedata()
{
if(!is_admin())
return;
if(!current_user_can('manage_options'))
return false;
$args = array(
'role' => 'customer', //client or whatever you required
);
//geting all user
$users = get_users( $args );
foreach ($users as $result)
{
//each user id
$userId = $result->ID;
if($userId != '')
{
//getting all user meta of particular user
$all_meta_for_user = get_user_meta( $userId );
if(is_array($all_meta_for_user))
{
foreach ($all_meta_for_user as $key => $value) {
# code...
$terms =get_user_meta($userid,'terms_and_conditions',true);
if($terms !=''){
delete_user_meta($userId, 'terms_and_conditions');
}
}
}
}
}
}

Updating entity in Doctrine takes too much time

I have the following code that updates SalesOrder Entity.
public function updateAction($id)
{
$securityContext = $this->get('security.context');
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('CIInventoryBundle:SalesOrder')->find($id);
$editForm = $this->createForm(new SalesOrderType($securityContext), $entity);
$currentTotal = $entity->getTotal();
$currentStatus = $entity->getStatus();
try {
$entity->isEditable();
} catch (\Exception $e){
$this->get('session')->setFlash('alert-error', $e->getMessage());
return $this->redirect($this->generateUrl('salesorder_show', array('id' => $entity->getId())));
}
$originalItems = array();
foreach ($entity->getItems() as $item) {
$originalItems[] = $item;
}
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()) {
try {
$entity->validateStatusChange($currentStatus, $currentTotal);
} catch (\Exception $e) {
$this->get('session')->setFlash('alert-error', $e->getMessage());
return $this->redirect($this->generateUrl('salesorder_show', array('id' => $id)));
}
foreach ($entity->getItems() as $item) {
//adjust the reserved in the inventory
$item->adjustReserved();
foreach ($originalItems as $key => $toDel) {
if ($toDel->getId() === $item->getId()) {
unset($originalItems[$key]);
}
}
}
foreach ($originalItems as $item) {
$em->remove($item);
}
$entity->setUpdatedAt(new \DateTime('now'));
$em->persist($entity);
$em->flush();
$this->get('session')->setFlash('alert-success', 'Record has been updated successfully!');
return $this->redirect($this->generateUrl('salesorder_show', array('id' => $id)));
} else {
$this->get('session')->setFlash('alert-error', 'Please fill in the correct values.');
$variantForm = $this->createForm(new AddVariantSalesOrderType());
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'variant_form' => $variantForm->createView(),
);
}
When i run this code i got ""maximum execution time exceeded". I already changed the maximum execution time in php.ini to 2 minutes.
Is there anyway i can optimize my codes ?
Thanks!

I can't get post request with symfony 2

I can't get the request POST this my code
public function inscriptionAction() {
$session = $this->getRequest()->getSession();
$request = Request::createFromGlobals();
$myCat = new \ stdClass;
$privatekey=$request->request->get('privatekey');
$key=$request->request->get('key');
if ($key== 'NULL' or $privatekey == NULL ) {
return $this->render('GestionsFilmeBundle:public:identification.html.twig', array(
'message' => 'Parametres non fournies-----',));
}
}
but privatekey and key are null
If you are using the Symfony Framework you don't need to build the Request object, you can just have it automatically injected in to your action and then you can use it from there.
public function inscriptionAction(Request $request) {
$privateKey = $request->request->get('privatekey');
$key = $request->request->get('key');
if (null === $key || null === $privateKey) {
return $this->render(
'GestionsFilmeBundle:public:identification.html.twig',
array(
'message' => 'Parametres non fournies-----',
)
);
}
}

Create form dynamically in Symfony 2

A simple question:
I have one form, it returns one number and I need create this number of labels in Controller.
I try:
$form2 = $this->createFormBuilder();
for($i = 0; $i < $num; $i++) {
$name = 'column'.$i;
$form2->add($name,'number');
}
$form2->getForm();
I think it should very simple, but i can't..
Yes, you can do it with an array / hash map instead of a real object.
Here is an example :
// Create the array
$dataObj = array();
$dataObj['data1'] = '';
$dataObj['data2'] = 'default';
// ... do a loop here
$dataObj['data6'] = 'Hello';
// Create the form
$formBuilder = $this->createFormBuilder($dataObj);
foreach($dataObj as $key => $val)
{
$fieldType = 'text'; // Here, everything is a text, but you can change it based on $key, or something else
$formBuilder->add($key, $fieldType);
}
$form = $formBuilder->getForm();
// Process the form
$request = $this->get('request');
if($request->getMethod() == 'POST')
{
$form->bind($request); // For symfony 2.1.x
// $form->bind($this->get('request')->request->get('form')); // For symfony 2.0.x
if($form->isValid())
{
$dataObj = $form->getData();
foreach($dataObj as $key => $val)
{
echo $key . ' = ' . $val . '<br />';
}
exit('Done');
}
}
// Render
return $this->render('Aaa:Bbb:ccc.html.twig', array(
'requestForm' => $form->createView()));

Resources