Get selected option and all request data in twig form - symfony

I have this form in twig, and I want to get the selected option and the value of the input field from a simple html form:
(PS: Don't say 'You'd better generate a form using the controller!' I know that, but I have a reason why I want to create a form in twig: because that allows me to create as many forms as I want using a for loop.)
I tried to pass arguments in the action path, but that didn't work.
<form action="{{ path('changeProf') }}" method="post" id="form">
<section class="col-lg-9 col-md-9 col-sm-9 col-xs-9" style="position: relative; left: 35%;top: 6vmin">
<label style="display:inline-table;">
<span> <input type="text" value="{{ user.id }}" disabled="true" id="iduser"style="max-width: 18vmin;"/></span>
</label>
</section>
<section class="col-lg-9 col-md-9 col-sm-9 col-xs-9"style="position: relative; left: 35%;top: 6vmin">
<label style="display:inline-table;">
<span>{% set k=1 %}
<select id="profil">
{% for prof in profArr %}
<option value="{{ prof }}"> {{ prof }} </option>
{% endfor %}
</select>
</span>
</label>
</section>
<input type="submit" class="btn btn-info btn-xs" style="position: relative;top:18vmin;left:-28%">
</form>
This is the action that handles the form :
/**
* #Route("/profile/chProf",name="changeProf")
* Method ("POST")
* #Template()
*/
public function changeProfAction(Request $request)
{
$session = new Session();
$session->start();
$search = $session->get('user');
$gestAcces = $session->get('acces');
$gestEtat = $session->get('etatUser');
$gestCont = $session->get('contenu');
$repMsg = $session->get('repMsg');
$gestRec = $session->get('Reclam');
$gestMess = $session->get('gestMess');
$gestMp = $session->get('gestMp');
if ($search == Null) {
return $this->redirectToRoute('empty', array('search' => $search,
'contenu' => $gestCont,
'gestAcces' => $gestAcces,
'gestEtat' => $gestEtat,
'repMsg' => $repMsg,
'gestRec' => $gestRec,
'gestMess' => $gestMess,
'gestMp' => $gestMp,
));
}
$em = $this
->getDoctrine()
->getManager();
$reposit = $em->getRepository("CNAMCMSBundle:userprof");
$rep = $em->getRepository("CNAMCMSBundle:profil");
$userprof=new userprof();
$libprof=$request->request->get('profil');
$iduser=$request->request->get('iduser');
$idprof=$rep->findOneBy(array('libelle'=>$libprof));
$userprof->setIdUser($iduser);
$userprof->setIdProfil($idprof);
$em->persist($userprof);
$em->flush();
return $this->render('CNAMCMSBundle:Default:userProf.html.twig', array(
'search'=>$search,
'contenu'=>$gestCont,
'gestAcces'=>$gestAcces,
'gestEtat'=>$gestEtat,
'repMsg'=>$repMsg,
'gestRec'=>$gestRec,
'gestMess'=>$gestMess,
'gestMp'=>$gestMp,
));
}

I think I found out what caused the error you receive.
$request->request->get('profil'); returns NULL.
This means, the form did not send a profil entry.
Look where is the profil in the form:
<input type="text" value="{{ user.id }}" disabled="true" id="iduser"style="max-width: 18vmin;"/>
There is no name attribute! Which is actually what is sent with the request. The name attribute, not the id. The id is used only for local styles and javascripts.
The solution:
<input type="text" value="{{ user.id }}" disabled="true" id="iduser" name="iduser" style="max-width: 18vmin;"/>
Do the same for profil
Hope this helps.

Related

symfony3 session parameter: adress['livraison'] give null value

I am experimenting with the implementation of ecommerce "DevAndClick". I cannot retrieve the delivery and billing addresses, and the session address[livraison] displays a null value. I am blocked. Has anyone ever met this problem that can help me?
Here is code of the form of the Twig view:
<form action="{{path('validation')}}" method="POST">
<h4>Adresse de livraison</h4>
{% for adresse in utilisateur.adresses %}
<label class="radio">
<input type="radio" name="livraison" value="{{adresse.id}}" {% if loop.index0 == 0 %} checked="checked" {% endif %} >
{{adresse.adresse}} , {{adresse.cp}} {{adresse.ville}}-{{adresse.pays}}<i class="icon-trash"></i> <br />
{{adresse.prenom}} {{adresse.nom}}
</label>
{% endfor %}
<br /><br />
<h4>Adresse de facturation</h4>
{% for adresse in utilisateur.adresses %}
<label class="radio">
<input type="radio" name="facturation" value="{{adresse.id}}" {% if loop.index0 == 0 %} checked="checked" {% endif %} >
{{adresse.adresse}} , {{adresse.cp}} {{adresse.ville}}-{{adresse.pays}}<i class="icon-trash"></i> <br />
{{adresse.prenom}} {{adresse.nom}}
</label>
{% endfor %}
<button class="btn btn-primary">Valider mes adresse </button>
</form>
Here are the two methods of my controller:
public function setLivraisonOnSession(Request $request)
{
$session = $request->getSession();
if(!$session->has('adresse')) $session->set('adresse',array());
$adresse = $session->get('adresse');
if($request->request->get('livraison') != null && $request->request->get('facturation') != null )
{
$adresse['livraison'] = $request->request->get('livrasion');
$adresse['facturation'] = $request->request->get('facturation');
}
else{
return $this->redirect($this->generateUrl('validation'));
}
$session->set('adresse',$adresse);
return $this->redirect($this->generateUrl('validation'));
}
public function validationAction(Request $request)
{
if($request->isMethod('POST'))
$this->setLivraisonOnSession($request);
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$adresse = $session->get('adresse');
//var_dump($adresse['livraison']);
// die();
$produits = $em->getRepository('EcommerceBundle:Produits')->findArray(array_keys($session->get('panier')));
$livraison = $em->getRepository('EcommerceBundle:UtilisateursAdresses')->find($adresse['livraison']);
$facturation = $em->getRepository('EcommerceBundle:UtilisateursAdresses')->find($adresse['facturation']);
return $this->render('EcommerceBundle:Default/panier/layout:validation.html.twig',array(
'produits' => $produits,
'livraison'=> $livraison,
'facturation'=>$facturation,
'panier'=>$session->get('panier')
));
}
Confirm that you have initialized your variable $adresse as an array before using it, like below:
$adresse = array();

How to upload an image using Sonata Media Bundle

I am working on a project using symfony.I want to use Sonata Media bundle,in order to upload image.
Unfortunately I don't knwo how to use it or how to start.
I havethis form :
<form action="" method="POST" class="filePhotoForm form-inline" role="form">
<div class="form-group">
<input type="button" class="btn btn-start-order browse" value="Browse">
<input type="text" class="form-control file-name" readonly="readonly" placeholder="No file selected">
<input type="file" name="filePhoto" id="filePhoto" class="hidden file-upload">
</div><br/><br/>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And the code in controller:
public function changePictureAction(Request $request)
{
return $this->render('MedAppBundle:Profile:change_picture.html.twig');
}
Can you help with the basics of uploading?
Thank you!
i have made a custom function for that
protected function saveImageMediaBundle($file,$context = 'default')
{
$mediaManager = $this->get('sonata.media.manager.media');
$media = new Media();
$media->setContext($context);
$media->setProviderName('sonata.media.provider.image');
$media->setBinaryContent($file);
$mediaManager->save($media);
return $media;
}
and get file by this
$file = $request->files->get('newsImage',null);
$media = $this->saveImageMediaBundle($file,'news');

Why function relates to code that is not in function?

I have the following controller:
<?php
namespace Dev\TaskBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
use Dev\TaskBundle\Entity\User;
class UserController extends Controller
{
/**
* Redirects to directory where you can input new password
*
* #Route("/{id}", name="user_update")
*/
public function userUpdatePanel($id)
{
$user = $this->getDoctrine()->getRepository('DevTaskBundle:User')->find($id);
return $this->render('DevTaskBundle:User:userUpdate.html.twig', array('user' => $user));
}
/**
* Updates password of the user
*
* #Route("/updatePassword", name="updatePass_action")
*/
public function passUpdateAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$id = $request->get('id');
$user = new User();
$user = $em->getRepository('DevTaskBundle:User')->find($id);
$password = $request->get('passInput');
$user->setPassword($password);
$em->flush();
$users = $this->getDoctrine()->getRepository('DevTaskBundle:User')->findAll();
return $this->render('DevTaskBundle:User:accounts.html.twig', array('users' => $users));
}
}
Here is form from userUpdate.html.twig
<form action="{{ path('updatePass_action') }}" method="POST">
<div>
Username: {{ user.username }}
</div>
<input type="hidden" name="id" value="{{user.id}}">
<div class="form-group">
<label for="passInput">Password:</label>
<input type="text" class="form-control" id="passInput" name="passInput" value="{{ user.password }}">
</div>
<button type="submit" class="btn btn-default">Change</button>
</form>
and when I proceed to change the password I receive such error
Impossible to access an attribute ("username") on a null variable in DevTaskBundle:User:userUpdate.html.twig at line 23
After changing the password I want to render accounts.html.twig so why there is the error about userUpdate? What is wrong here?
Part of accounts.html.twig with twig scripts:
<table class="table table-bordered">
<thead>
<tr>
<th>Login</th>
<th>Hasło</th>
<th>Narzędzia</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>
{{ user.username }}
</td>
<td>
{{ user.password }}
</td>
<td>
<a href="{{ path('user_update', {'id': user.id}) }}" >
<span class="glyphicon glyphicon-pencil linkDeco" ></span>
</a>
{% if user.status == 1 %}
<a href="{{ path('deleteAction', {'name': 'User' ,'direction': 'account_panel' , 'id': user.id}) }}" >
<span class="glyphicon glyphicon-trash linkDeco"></span>
</a>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
EDIT
problem must be related to userUpdate.html.twig because when I deleted
<div>
Username: {{ user.username }}
</div>
I have the error
Impossible to access an attribute ("id") on a null variable in DevTaskBundle:User:userUpdate.html.twig at line 24
Any idea why is that?
Doctrine find method return array of objects, use findOne instead of find when you expecting only one result.
$user = $this->getDoctrine()->getRepository('DevTaskBundle:User')->findOneById($id);

Add action in Symfony2

In the show page i whant add order quantity in my session.
This is my action
/**
* #Route("/add/{id}", name="add_action")
* #param Request $request
* #param $id
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function addAction(Request $request, $id)
{
$session = $request->getSession();
$basket = $session->get('basket');
$key = array_search($id, $basket);
if(!$key)
{
$basket[$key] = $request->query->get('item');
$session->set('basket', $basket[$key]);
}
return $this->redirectToRoute('basket_action');
}
In this action i have error Warning: array_search() expects parameter 2 to be array, null given. What can be done to make it work?
P.S.
part of my template
<form method="get" action="{{ path('add_action', {'id' : product.id}) }}">
<select class="form-control" name="item">
{% for i in 1..10 %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
<button class="btn btn-success" >Add to basket</button>
</form>
change
$basket = $session->get('basket');
to
$basket = $session->get('basket', array());
Looks like you are not storing basket as an array on session correctly, I would need to see your code where stores it. You can add a check if is an array before using array_search to prevent this error

Overlapping forms

I have a problem with overlapping forms in Symfony 2. I'm trying to create an application with photos albums.
To do so, I need to create an album and adding him photos during this process.
Photos are link with onl one album.
I think that my code is right on backend but the photo's form never shown inside the album's form. I think the problem is in the form himself.
A photo have to attribute: a file and a name.
This is my form.
<script type="text/javascript">
$(document).ready(function() {
var $container = $('#thelink_albumbundle_albumtype_photos');
function add_photo() {
index = $container.children().length;
$container.append(
$($container.attr('data-prototype').replace(/\$\$picture\$\$/g, index))
);
}
if($container.children().length == 0)
add_tag();
$('#add_photo').click(function() {
add_photo();
});
});
<form method="post" enctype="multipart/form-data">
{{ form_widget(form) }}
<div id="thelink_albumbundle_albumtype_photos" data-prototype="<div>
<label class=" required">$$photo$$</label>
<div id="thelink_albumbundle_albumtype_photos$$photo$$">
<div><label for="thelink_albumbundle_albumtype_photos$$photo$$_photo"
class=" required">Photo</label>
<input type="file" id="thelink_albumbundle_albumtype_photos$$photo$$_photo"
name="thelink_albumbundle_albumtype[photos][$$photo$$][picture]" required="required"
maxlength="255" value="" /></div></div></div>">
</div>
<br />
<a href="{{ path('TheLinkAlbumBundle_index') }}" title="Retourner sur la liste des Albums">
Annuler la {% if news is defined %}Modification{% else %}Création{% endif %}
</a>
<input type="submit" value="{% if album is defined %}Modifier{% else %}Créer{% endif %} l'Album" />
Do you have any idea ? Or the problem is else where ?
It looks like you're manually entering the data prototype? Assuming "photos" is a collection type. Make sure you have the "allow_add", "allow_delete", and "prototype" options set to true:
->add('photos', 'collection', array(
'type' => new PhotoType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true
))
Then you can just do {{ form_row(form.photos) }} and it should render the prototype automatically.
It would help more if you could post your form type as well.

Resources