Using Django, how do I set a ModelForm field value dynamically in the template? - forms

I'm trying to utilize a checkbox field to create a model instance for a user selected favorite. The last piece I need in order for this to work properly is to set the default value in one of the form fields equal to the value in a loop. Would I do this with the initialize argument, in the views.py file, in the form itself, or in the template? Here is the associated code:
Apologies for the HTML class tags
models.py
class ReportDirectory(models.Model):
report_name = models.CharField(max_length=300, unique=True, blank=False)
report_desc = models.TextField()
report_type = models.CharField(max_length=300)
report_loc = models.TextField()
slug = models.SlugField(unique=True, max_length=300)
last_update = models.DateTimeField(null=True)
main_tags = models.CharField(max_length=300)
# Renames the item in the admin folder
def __str__(self):
return self.report_name
class Favorite(models.Model):
directory_user = models.ForeignKey(User, on_delete=models.CASCADE)
user_report = models.ForeignKey(ReportDirectory, on_delete=models.CASCADE)
favorited = models.BooleanField(default=False)
def __str__(self):
return str(self.directory_user)+" - "+str(self.user_report)
forms.py
from django import forms
from .models import Favorite
class FavoriteForm(forms.ModelForm):
class Meta:
model = Favorite
fields = '__all__'
widgets = {
'favorited': forms.CheckboxInput(attrs={
'type':'checkbox',
'name':'checkbox',
'onchange':'submit()'
})
}
views.py
from django.shortcuts import render,redirect
from django.views import generic
from .models import ReportDirectory, Favorite
from django.contrib.auth.models import User
from .forms import FavoriteForm
def report_directory(request):
favorite = Favorite.objects.filter(directory_user=request.user.id, favorited=True)
reports = ReportDirectory.objects.exclude(favorite__directory_user=request.user.id, favorite__favorited=True)
favform = FavoriteForm(initial={'directory_user':request.user},)
context = {
'reports':reports,
'favorite':favorite,
'favform':favform
}
if request.method == 'POST':
form = FavoriteForm(request.POST)
if form.is_valid():
form.save()
return redirect('/report_directory')
return render(request, 'counter/report_directory.html',context)
html
<thead>
<tr>
<th class="gls-table-expand">Favorite</th>
<th onclick="sortTable(1)" class="gls-table-expand">Report Type</th>
<th onclick="sortTable(2)" class="gls-table-expand">Report Name</th>
<th class="gls-table-expand">Report Description</th>
<th onclick="sortTable(3)" class="gls-table-expand">Last Updated</th>
<th class="gls-table-expand">Main Tags</th>
<th onclick="sortTable(4)" class="gls-table-expand">View Count</th>
</tr>
</thead>
<tbody id="myTable">
{% for r in reports.all %}
<tr report-name="{{ r.report_name }}">
<td>
<form method="POST">
{% csrf_token %}
{{ favform.favorited }}
</form>
</td>
<td><span><img img width="20" height="20"
{% if r.report_type == 'Tableau' %}
src=" {% static 'images/tableau_icon.svg' %}"
{% elif r.report_type == 'Excel' %}
src=" {% static 'images/excel_icon.svg' %}"
{% elif r.report_type == 'Box' %}
src=" {% static 'images/excel_icon.svg' %}"
{% elif r.report_type == 'Internal Report' %}
src=" {% static 'images/www_icon.svg' %}"
{% endif %}
></span> {{ r.report_type }}</td>
<td>{{ r.report_name }}</td>
<td>{{ r.summary }}</td>
<td><p class="gls-text-meta gls-margin-remove-top">{{ r.last_update_format }}</p></td>
<td>{{ r.main_tags }}</td>
<td>{% get_hit_count for r %}</td>
</tr>
{% endfor %}
</tbody>

I found a solution to dynamically iterate through the template and complete the ForeignKey (selection) field. I needed to set the for iterator equal to the selection option
<form method="POST" id="{{ r.report_name }}">
{% csrf_token %}
<p hidden>
{{ favform.directory_user }}
<select name="user_report" required="" id="id_user_report">
<option value="{{ r.id }}" selected></option>
</select>
</p>
{{ favform.favorited }}
</form>
I feel like I'm working against Django forms, however, and not with the infrastructure...

Related

How to update multiple objects by one html request?

I have a problem and can't find a decision.
I need to update a value for several objects by one form. If I did it one by one, without submit button it works fine. But I want to do it by click to one button.
My HTML form:
<form method="post" action="{% url 'installmentreport-update' %}">
{% for installmentreport in installment.installmentreport_set.all %}
<tr>
<td class="align-middle" style="text-align:center">{{installmentreport.title}}</td>
<td class="align-middle" style="text-align:center">
{% csrf_token %}
<input type="number" name='spent' value={{installmentreport.spent}} placeholder={{installmentreport.spent}} size="8">
<input type="hidden" name='id' value={{installment.id}}></td>
<input type="hidden" name='pk' value={{installmentreport.id}}>
</tr>
{% endfor %}
<td></td>
<td class="align-middle" style="text-align:center"><input type="submit" class="btn btn-warning" name="submit" value="Update"></form>
Views:
class InstallmentReportUpdate(LoginRequiredMixin,PermissionRequiredMixin,UpdateView):
model = InstallmentReport
permission_required = 'catalog.can_change_program'
fields = ['spent']
def get_object(self):
pks = self.request.POST.getlist('pk')
for pk in pks:
return InstallmentReport.objects.get(pk=pk)
def form_valid(self, form):
if self.request.method == 'POST':
spents = self.request.POST.getlist('spent')
if form.is_valid():
for spent in spents:
instance = form.save(commit=False)
form.instance.spent = spent
instance.save()
return super().form_valid(form)
def get_success_url(self):
id = self.request.POST.get('id')
return reverse('installment-detail-owner', args=[str(id)])
I use Python3.7 and Django2.2
I did it!
Views:
def get_object(self):
pks=self.request.POST.getlist('pk')
spents = self.request.POST.getlist('spent')
for pk, spent in zip(pks,spents):
print(pk)
print(spent)
InstallmentReport.objects.filter(pk=pk).update(spent=spent)
return InstallmentReport.objects.get(pk=pk)

symfony paginator + filter form

I'm new to Symfony, I got a page in where I have a list of articles, and I created a form above it that allow me to filter the results of my query :
The form works fine, but when I click on the 2nd page of my paginator table, the form reset, so my filter is reset too. What I want is that we can filter results and be able to paginate the table, with the same filter, and that the form keep his data.
Here's my code right now :
Controller :
public function listeAction(Request $request, $page) {
if ($page < 1 && strlen($page) != 0) {
throw new NotFoundHttpException('Page "' . $page . '" inexistante.');
} else if (strlen($page) == 0) {
$page = 1;
}
$nbPerPage = 5;
$form = $this->createForm(ArticleRechercheType::class);
$form->setData(array('rds' => true));
//if we use filters
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$data = $form->getData();
$form = $this->createForm(ArticleRechercheType::class, $data);
if ($data['famille'] != null) {
$data['famille'] = $data['famille']->getId();
}
$listArticles = $this->getDoctrine()
->getManager()
->getRepository('GRBackOfficeBundle:Article')
->getFilteredArticles($page, $nbPerPage, $data);
} else {
$data = $form->getData();
$form = $this->createForm(ArticleRechercheType::class, $data);
$listArticles = $this->getDoctrine()
->getManager()
->getRepository('GRBackOfficeBundle:Article')
->getArticles($page, $nbPerPage);
}
$nbPages = ceil(count($listArticles) / $nbPerPage);
if ($nbPages != 0 && $page > $nbPages) {
throw new NotFoundHttpException('Page "' . $page . '" inexistante.');
}
if ($nbPages == 0) {
$nbPages = 1;
}
return $this->render('GRBackOfficeBundle:Article:liste_articles.html.twig', array(
'form' => $form->createView(),
'listArticles' => $listArticles,
'nbPages' => $nbPages,
'page' => $page
));
}
Form :
class ArticleRechercheType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('famille', EntityType::class, array(
'class' => 'GRBackOfficeBundle:Famille',
'choice_label' => 'nom',
'required' => false
))
->add('rds', CheckboxType::class, array('required' => false))
->add('recherche', TextType::class, array('required' => false))
->add('Rechercher', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'translation_domain' => false
));
}
}
View :
{% extends "GRBackOfficeBundle::layout.html.twig" %}
{% block title %}
Liste des articles
{% endblock %}
{% block gr_bo_body %}
<h2>Liste des articles</h2>
<div class="row">
<div class="well row">
{{ form_start(form) }}
{{ form_errors(form) }}
<div class="form-group col-md-2">
{{ form_label(form.famille, "Famille d'article", {'label_attr': {'class': 'control-label'}}) }}
{{ form_errors(form.famille) }}
{{ form_widget(form.famille, {'attr': {'class': 'form-control'}}) }}
</div>
<div class="form-group col-md-4">
{{ form_widget(form.rds, {'attr': {'class': ''}}) }}
{{ form_label(form.rds, "Montrer les articles en rupture de stock", {'label_attr': {'class': 'control-label'}}) }}
{{ form_errors(form.rds) }}
</div>
<div class="form-group col-md-3">
{{ form_label(form.recherche, "Recherche", {'label_attr': {'class': 'control-label'}}) }}
{{ form_errors(form.recherche) }}
{{ form_widget(form.recherche, {'attr': {'class': 'form-control'}}) }}
</div>
<div class="form-group col-md-3" style="text-align: center">
{{ form_widget(form.Rechercher, {'attr': {'class': 'btn btn-primary'}}) }}
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
<div class="well row">
<table class="table table-bordered table-striped" id="listeArticles" style="width: 100%" cellspacing="0">
<thead>
<tr>
<th>Référence client</th>
<th>Référence interne</th>
<th>Famille</th>
<th>Libellé</th>
<th>Alerte</th>
<th>Stock</th>
</tr>
</thead>
<tbody id="bodyListeArticles">
{% for article in listArticles %}
<tr>
<td>{{ article.RefArticle }}</td>
<td>{{ article.RefLogistique }}</td>
<td>{{ article.famille.nom }}</td>
<td>{{ article.libelle }}</td>
<td>{{ article.StockAlerte }}</td>
<td>{{ article.StockActuel }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if nbPages > 1 %}
<ul class="pagination">
{% for p in range(1, nbPages) %}
<li {% if p == page %} class="active"{% endif %}>
{{ p }}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
</div>
{% endblock %}
If anyone have an idea of how I can do that, that will be appreciated
You can use a bundle (like the knp paginator bundle for exemple), or put your args in session. But the bundle will make it simple as it does everything for you, you just have to pass your datas

Python Django edit data in database by forms (django v.1.9.4)

My goal is add data to database via form and make them editable via edit form.
My error:
Exception Type: NoReverseMatch at /testtable/car/new/
Exception Value: Reverse for 'car_list' with arguments '()' and keyword arguments '{'pk': 2}' not found. 0 pattern(s) tried: []
and next problem is how to make a link to edit data
in template/car_list.html to car_edit.html.
<td>Delete</td>
<td>Edit Delete</td>
When I type manually in Explorer http://localhost:8000/testtable/car/1/ it works, I see details of first article in database, but forms with pk arguments doesnt work.
MyApp/testtable/models.py
from django.db import models
import datetime
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class TableParemeters(models.Model):
author = models.ForeignKey('auth.User')
car_brand = models.CharField(max_length=20)
car_type = models.CharField(max_length=20)
car_colour = models.CharField(max_length=20)
car_fuel = models.CharField(max_length=20)
car_trans = models.CharField(max_length=20)
car_license_plate = models.CharField(max_length=20)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return "%s %s" % (self.car_brand, self.car_type)
MyApp/testtable/views.py
from django.shortcuts import redirect, get_object_or_404, render_to_response, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import loader
from django.views import generic
from django.utils import timezone
from django.template import RequestContext
from django.core.context_processors import csrf
from django.contrib.auth.models import User
from .models import TableParemeters
from .forms import CarForm
def car_list(request):
cars = TableParemeters.objects.all().order_by('id')
return render(request, 'testtable/car_list.html', {'cars': cars})
def car_detail(request, pk):
car = get_object_or_404(TableParemeters, pk=pk)
return render(request, 'testtable/car_detail.html', {'car': car})
def car_new(request):
if request.method == "POST":
form = CarForm(request.POST)
if form.is_valid():
car = form.save(commit=False)
car.save()
return redirect ('car_list', pk=car.pk)
else:
form = CarForm()
return render(request, 'testtable/car_new.html', {'form': form})
def car_edit(request, pk):
car = get_object_or_404(TableParemeters, pk=pk)
if request.method == "POST":
form = CarForm(request.POST, instance=car)
if form.is_valid():
car = formsave(commit=False)
car.save()
return redirect('car_detail', pk=car.pk)
else:
form = CarForm(instance=car)
return render(request, 'testtable/car_edit.html', {'form': form})
MyApp/testtable/forms.py
from django import forms
from .models import TableParemeters
class CarForm(forms.ModelForm):
class Meta:
model = TableParemeters
fields = '__all__'
MyApp/testtable/urls.py
from django.conf.urls import include, url
from . import views
app_name = 'testtable'
urlpatterns = [
#login
#url(r'^$', views.login_page, name='login'),
#logout
#carlist url
url(r'^$', views.car_list, name='car_list'),
#detail car url
url(r'^car/(?P<pk>\d+)/$', views.car_detail, name='car_detail'),
#add new car to list url
url(r'^car/new/$', views.car_new, name='car_new'),
#edit car in the list
url(r'^car/(?P<pk>\d+)/edit/$', views.car_edit, name='car_edit'),
]
MyApp/testtable/template/testtable/car_list.html
{% extends 'testtable/base.html' %}
{% block content %}
<table class="table table-striped">
<tbody>
<tr>
<th>ID</th>
<th>Brand</th>
<th>Type</th>
<th>Colour</th>
<th>Fuel</th>
<th>Transmition</th>
<th>License Plate</th>
<th>Created Date</th>
<th>Author</th>
<th></th>
</tr>
{% for testtable in cars %}
<tr>
<td>{{ testtable.car_id }}</a></td>
<td>{{ testtable.car_brand }}</a></td>
<td>{{ testtable.car_type }}</td>
<td>{{ testtable.car_colour }}</td>
<td>{{ testtable.car_fuel }}</td>
<td>{{ testtable.car_trans }}</td>
<td>{{ testtable.car_license_plate }}</td>
<td>{{ testtable.created_date }}</td>
<td>{{ testtable.author }}</td>
<td>Delete</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
I mean, that car_list not need pk and django can't found any url for car_list with parameter.
Maybe you can try replace line:
return redirect ('car_list', pk=car.pk)
with:
return redirect ('car_list')

Render custom entity type field in form (Symfony)

I got stuck while trying to customize the rendering of a specific field in my form.
It looks like this:
$builder->add('players', 'entity', array(
'class' => 'Acme\Bundle\Entity\Player',
'expanded' => true,
'multiple' => true,
'required' => false,
));
The form itself is beeing rendered with a simple:
{% block form_content %}
{% form_theme form 'AcmeBundle:Form:fields_child.html.twig' %}
{{ form_widget(form) }}
{% endblock %}
Now inside fields_child.html.twig i'm extending from another form template but there is nothing special there.
My HTML looks like this:
Players:
- [checkbox-input] 1
Where 1 equals the id of the only player in the database. However instead of rendering the ID im trying to render his picture and full name after the checkbox.
I have tried many combinations of the form theming to override it but failed each time.
Could someone post the twig block to render what i want here?
Thanks
You have to create custom form field type together with custom widget template for it.
http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html
I recently ran into this problem (was a little bit different situation. I needed to show products as table with checkboxes..), Form's child data always returned null value that's why I ended up with this (dirty:)) solution:
Controller action:
...
$productRepository = $entityManager->getRepository('VendorMyBundle:Product');
$products = [];
$formChildren = $productListForm->createView()->children;
foreach ($formChildren['products'] as $formProduct) {
$formProductId = $formProduct->vars['value'];
$productEntity = $productRepository->find($formProductId);
$products[$formProductId] = $productEntity;
}
...
return $this->render('TEMPLATE', [
'productListForm' => $productListForm->createView(),
'products' => $products,
]);
Template:
...
{% for productForm in productListForm.products %}
{% set id = productForm.vars.value %}
<tr>
<td class="check">
{{ form_widget(productForm) }}
</td>
<td class="photo">
{% if products[id].getImages().isEmpty() == false %}
{% set productImage = products[id].getImages().first() %}
<img src="{{ productImage.getWebPath() | imagine_filter('st_product_cabinet_thumbnail') }}" />
{% else %}
<span class="no-image">No image</span>
{% endif %}
</td>
<td class="title">
{{ products[id].getName() }}
</td>
<td class="status">
{{ products[id].getStatusName(products[id].getStatus()) }}
</td>
<td class="price">
<ul>
{% for productPrice in products[id].getPrices() %}
<li>{{ productPrice.getValue() ~ ' ' ~ productPrice.getCurrencyCode() }}</li>
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
...

Get form from rendered controller

I have such problem with symfony2.
I have base.html.twig and this base is the template for others twigs.
I want to render controller, which contains form with locale-type input field.
The form will be used to change language of site.
My LanguageController:
<?php
namespace Soczewki\PlatformaBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class LanguageController extends Controller {
public function createAction(Request $Request)
{
$form = $this->createFormBuilder()
->setMethod('POST')
->setAction(null)
->add('locale', 'locale', array(
'label' => ' ',
'choices' => array('pl' => 'Polski', 'de' => 'Deutsch', 'en' => 'English'),
'data' => $this->getRequest()->getLocale(),
'required' => true))
->add('submit', 'submit')
->getForm();
$form->handleRequest($Request);
if($form->isValid()) {
$this->getRequest()->setLocale('en');
}
return $this->render("SoczewkiPlatformaBundle::myForm.html.twig",
array(
'form' => $form->createView(),
'req' => $r
));
}
}
The whole base.html.twig:
<html>
<head>
<title>{% block pageTitle %}{% endblock %}</title>
{#js#}
<script src="{{ asset('bundles/soczewkiplatforma/js/jquery.js') }}"></script>
<script src="{{ asset('bundles/soczewkiplatforma/js/bootstrap.js') }}"></script>
{#/js#}
{% block stylesheets %}
<link href="{{ asset('bundles/soczewkiplatforma/css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ asset('bundles/soczewkiplatforma/css/my-style.css') }}" rel="stylesheet">
{% endblock stylesheets %}
</head>
<body>
{% if app.security.getToken().getUser().getAuthKey() is defined %}
{% if app.security.getToken().getUser().getAuthKey() is not empty %}
{% set diff = ( app.security.getToken().getUser().getEndDate()|date('U') - "now"|date('U') ) / 3600 %}
<div style="width: 300px; height: 140px; position: absolute; bottom: 90px; right: 50px;" class="alert alert-danger alert-error">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<strong>Uwaga!</strong> Twoje konto nadal nie zostało aktywowane!<br />
Pozostało Ci: <span class="badge">{{ diff[0:2] }} godzin {{ ( diff[3:] * 60 )[0:2] }} minut </span>
<br /><br />
<button type="button" class="btn btn-danger">Wpisz kod</button>
<button type="button" class="btn btn-default" data-dismiss="alert">Zamknij</button>
</div>
{% endif %}
{% set hasParams = app.request.get('id') %}
{% if hasParams is empty %}
{% set currentPath = url( app.request.attributes.get( '_route', app.request.attributes.get('_route_params'))) %}
{% else %}
{% set currentPath = url( app.request.attributes.get( '_route', app.request.attributes.get('_route_params')),{'id': 0} ) %}
{% endif %}
{% set dirs = currentPath|split('/') %}
{% set flag = "" %}
{% set url = "" %}
<ol class="breadcrumb">
<li>Główna</li>
{% for key, dir in dirs %}
{% if url is not empty %}
{% set url = url ~ '/' ~ dir %}
{% else %}
{% set url = url ~ dir %}
{% endif %}
{% if flag == true %}
{% if '=' in dir %}
{% set _temp = dir|split('=') %}
{% else %}
{% set _temp = dir|split(' ') %}
{% endif %}
{% if key + 1 == dirs|length %}
<li class="active"> {{ _temp[0]|capitalize|replace('-',' ') }} </li>
{% else %}
<li> {{ _temp[0]|capitalize|replace('-',' ') }} </li>
{% endif %}
{% endif %}
{% if dir == 'app_dev.php' %}
{% set flag = true %}
{% endif %}
{% endfor %}
<li class="dropdown" style="float: right !important;">
Zalogowano jako: {{ app.security.getToken().getUser().getName() }} <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Moje konteło</li>
<li>Wyloguj</li>
</ul>
</li>
</ol>
{% else %}
<ol class="breadcrumb">
<li>Główna</li>
<!--- logowanie --->
<li class="dropdown" style="float: right !important;">
Zaloguj <span class="caret"></span>
<div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px; left: -200px;">
<form action="{{ path('login_check') }}" method="post">
<label for="username">Email/NIP:</label>
<input type="text" id="username" name="_username" />
<br />
<label for="password">Hasełko:</label>
<input type="password" id="password" name="_password" />
<br /><br />
<button type="submit">Loguj do Afganistanu</button>
</form>
</div>
</li>
<!--- log ---->
</ol>
{% endif %}
{{ render(controller('SoczewkiPlatformaBundle:Language:create')) }}
{% block pageContainer %}
{% endblock %}
</body>
</html>
Nothing shows and I get too any error.
Why is it like that?
// codes updated
myForm.html.twig:
{{ dump(req) }}
{{ form(form) }}
and LocaleListener.php:
<?php
namespace Soczewki\PlatformaBundle\Translations;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'pl')
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
You have created a situation where you are calling the same method an infinite amount of times until the page just dies.
You original base is being rendered which is in the end rendering the SoczewkiPlatformaBundle::base.html.twig template. Within this template a render() is calling an action that is then rendering the SoczewkiPlatformaBundle::base.html.twig template, which then calls the render(), which then render SoczewkiPlatformaBundle::base.html.twig, and on and on...
You need to specify a template for the form to be rendered in rather than the base and then call that in your changeAction.
For example...
Soczewki\PlatformaBundle\Controller\LanguageController
public function changeAction(Request $Request)
{
// ..
return $this->render("SoczewkiPlatformaBundle:Locale:change_form.html.twig",
array(
'form' => isset($form) ? $form->createView() : null,
));
}
SoczewkiPlatformaBundle:Locale:change_form.html.twig
{{ form_start(form, {'method': 'POST', 'action': 'your_locale_change_route' }) }}
{{ form_row(form.locale) }}
{{ form_end(form) }}
Your next problem would be that your changeAction isn't actually performing an action (apart from creating a form), although you may just be wanting that page to show before you get to that part.
You need to add this code where you want that the form appear
{{ form(form) }}
Edited after the comments below;
Create a file named myForm.html.twig and put in SoczewkiPlatformaBundle;
Now write this code inside:
{{ form(form) }}
now your controller should be:
public function changeAction(Request $Request)
{
$form = $this->createFormBuilder()
->add('locale', 'locale', array(
'label' => 'user.locale',
'required' => true,
'choices' => array('en' => 'English', 'de' => 'Deutsch', 'pl' => 'Polish')
))
->getForm();
$form->handleRequest($Request);
return $this->render("SoczewkiPlatformaBundle::myForm.html.twig",
array(
'form' => $form->createView(),
));
}