I'd like to use the same view for both editing and viewing. Unfortunatly, I cannot edit my view. In symfony3, I think there is no way to index a form. I tried every thing I could but I don't know how I can use the same form. In my project, I use also JEE (linked directly to data base) to communicate with symfony using UniRest API. Here are my view and edit controllers:
/**
* #Method({"GET"})
*/
public function viewAction($id) {
$phone = new Phone();
$form = $this->createForm(PhoneType::class, $phone);
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::get(link/phones/'.$id,$headers);
//$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
return $this->render('AppBundle:Phone:PhoneView.html.twig', array (
'form' => $form->createView(),
'phone' => $response->body,
) );
}
/**
* #Method({"PUT"})
*/
public function updateAction(Request $request, $id) {
$phone = new Phone();
$form = $this->createForm(PhoneType::class, $phone);
dump($request->getMethod());
if ($request->isMethod('PUT')) {
$form->handleRequest($request);
$headers = array('Content-Type' => 'application/json');
$data = json_encode($phone);
$response = Unirest\Request::put('link/phones/'.$id,$headers,$data);
//$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
dump($response->code);
return $this->redirect($this->generateUrl('phones_list'));
}
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::get('link/phones/'.$id,$headers);
//$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
dump($response->code);
dump($response->body);
return $this->render('AppBundle:Phone:PhoneUpdate.html.twig', array(
'form'=> $form->createView(),
'phone'=> $response->body,
));
And here is my file PhoneView.html.twig
{% extends "::base.html.twig" %}
{% block title %}Accedant - {{ parent() }}{% endblock %}
{% block body %}
<form novalidate="novalidate" method = "get">
<p>
<label> color </label> :<input type="text" value= {{ phone.color }} />
<label> price </label> :<input type="text" value= {{ phone.price }} />
<div class="form-group col-md-offset-5">
<button type="submit" class="btn btn-default">Save</button>
</div>
</p>
</form>
{# Updating Phone #}
<p class="left-center">
<a href="{{ path('phones_update', {'id': phone.id}) }}" class="btn btn-mini btn-danger" class="btn btn-mini btn-danger">
Modify phone
</a>
</p>
{% endblock %}
And here is my PhoneUpdate.html.twig
{% extends "::base.html.twig" %}
{% block title %} Phone - {{ parent() }}{% endblock %}
{% block body %}
<div class="container">
{{ form_start(form, {'method': 'PUT'}) }}
<input type="hidden" name'_METHOD' value="PUT">
{{ form_widget(form) }}
<input type="submit" value="Sauvegarder" class="btn btn-default" />
{{ form_end(form) }}
</div>
{% endblock %}
and here is my file routing.yml
phones_view:
path: /phones/{id}
defaults: { _controller: AppBundle:Phone:view }
methods: [GET]
requirements:
id: \d+
phones_update:
path: /phones/{id}
methods: [PUT]
defaults: { _controller: AppBundle:Phone:update }
requirements:
id: \d+
Thank you for your help.
First of all, my put and delete method was not configurated. Moreover, my problem was that I thought that the put method in my routing file routing.yml has no relation with my web services. So I change my path in order to edit my form /update/{id}, and after that I got a 404 error that was because of my implementation in J2EE side.
Related
I have a strange problem on symfony 6.1
I searched, but I couldn't find the solution.
The error message: Neither the property "_token" nor one of the methods "_token()", "get_token()"/"is_token()"/"has_token()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".
The error occurs when validation fails Error screen
#[Route('/new', name: 'app_commande_new', methods: ['GET', 'POST'])]
public function new(Request $request, ProductRepository $productRepository): Response
{
$commande = new Commande();
$form = $this->createForm(CommandeType::class, $commande);
//dd($request);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
dd($form->getData());
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
//dd($form);
return $this->renderForm('commande/new.html.twig', [
'commande' => $commande,
'form' => $form,
]);
}
View
{{ form_start(form) }}
<div class="row">
<div class="col-md-6">
{{ form_row(form._token) }}
{{ form_row(form.client) }}
</div>
<div class="col-md-6">
{{ form_row(form.limitDate) }}
</div>
</div>
<button class="btn btn-primary" id="save" type="submit">{{ button_label|default('Save') }}</button>
{{ form_end(form, {render_rest: false}) }}
My post can't take more code here are the pictures of the forms code.
CommandeType
ProductOutType
I'm trying to print the value of the input field 'gameTitle' in Twig.
This is my code:
<h1>New game</h1>
<form method="post" action="">
<label>Game Title</label>
<input type="text" value="Monopoly" name="gameTitle"><br>
<input class="btn btn-success" name="submit" type="submit" value="Add game">
</form>
{% if app.request.post('submit') %}
{{ app.request('gameTitle')}}
{% endif %}
I've also tried:
{{ app.request.parameter.post('gameTitle}
As a result I want to print this result: "gameTitle is Monopoly".
My question, how do I do the following PHP code in Twig?
<?php
echo "gameTitle is ".$_POST['gameTitle'];
?>
Update:
- I'm not using Symfony, just Twig: http://twig.sensiolabs.org/
This does not work for me:
{{app.request.post('gameTitle')}}
{{app.request.request.get('gameTitle')}}
{{ app.request.request.get("gameTitle") }}
gameTitle is {{ app.request.request.post('gameTitle') }}
As far as I can see, the vanilla Twig doesn't provide access to the request variables by default. You should pass them to the template explicitly, e.g.:
require __DIR__ . '/vendor/autoload.php';
$loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');
$twig = new Twig_Environment($loader, array(
'cache' => __DIR__ . '/tpl_cache',
));
echo $twig->render('template.twig', ['post' => $_POST]);
Then use it as follows:
{% if post.gameTitle is defined %}
Game title: {{ post.gameTitle }}
{% endif%}
You should use
{{ app.request.request.get("gameTitle") }}
It has been changed.
I have started to study Symfony2 since I will probably need in my work.
routing.yml:
account_register:
path: /register
defaults: {_controller: AppBundle:Register:index}
RegisterController:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\User;
class RegisterController extends Controller
{
/**
* #Route("/register")
*/
public function indexAction(Request $request)
{
$register = new User();
$form = $this->createFormBuilder($register)
->add('email', 'email', array('required' => false))
->add('password', 'password', array('required' => false))
->add('alias', 'text', array('required' => false))
->add('register', 'submit', array('label' => 'Register'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database
$em = $this->getDoctrine()->getManager();
$em->persist($register);
$em->flush();
exit("Error");
//return $this->redirectToRoute('task_success');
}
return $this->render('pages/register.html.twig', array(
'form' => $form->createView(),
));
}
}
regiser.html.twig:
{% extends 'base.html.twig' %}
{% block body %}
<br /><br />
<div class = "window">
<form>
<br /><br /><br /><br /><br /><br /><br />
{{ form_start(form) }}
{{ form_errors(form) }}
<div id=center-text>Email</div>
<div class="textfield" id=center> {{ form_widget(form.email, {'attr': {'class': 'textfield', 'size': '22', 'maxlength': '100'}}) }} </div>
<br />
<div id=center-text>Password</div>
<div class="textfield" id=center> {{ form_widget(form.password, {'attr': {'class': 'textfield', 'size': '22', 'maxlength': '100'}}) }} </div>
<br />
<div id=center-text>Alias</div>
<div class="textfield" id=center> {{ form_widget(form.alias, {'attr': {'class': 'textfield', 'size': '22', 'maxlength': '100'}}) }}</div>
<br /><br />
<br />
<center>
{{ form_widget(form.register, {'attr': {'class': 'button'}}) }}
</center>
{{ form_end(form) }}
</form>
{% endblock %}
When i press the submit button only the url changes from http://localhost/website/web/app_dev.php/register
to
http://localhost/website/web/app_dev.php/register?form%5Bemail%5D=&form%5Bpassword%5D=&form%5Balias%5D=&form%5Bregister%5D=&form%5B_token%5D=hd70y_KjUEY8v51dQjnjU0ZMTJ0BYOihurV6IcIvghY
What is happening is the expected form's flow. The form that you are submitting is redirecting to the same page.
If you don't want your form to be in GET, you can change it for POST :
$form = $this->createFormBuilder($register)
->setMethod('POST')
->...
When you are redirected after submitting the form, $form->handleRequest($request) binds the request (your data submitted) with the form that is just created. $form->isValid() then checks if your data is valid according to your form.
If you don't see any change after being redirected, you should check if $form->isValid() returns true.
If you want to redirect your form to another controller method, you should create another resource and then set the action attribute of your form thanks to the setAction() method.
To sum up, everything that I just told you is written and explained on this page, and you definitely should read it ! :-).
Silly me, the html was my test code and then i added the symfony {{ blocks }} and forgot to remove the old tags
I've followed the guide and gotten the registration working just fine.
The only issue I have with this is the Form has a title:
User
I do not want this title. I want to customize this. How do I change this title.
As for code everything is as in the guide except my controller which is:
/**
* #Route("/SignUp", name="wx_exchange_signup")
* #Template("WXExchangeBundle:User:signup.html.twig")
* #Method({"GET"})
* User sign up - Open to public
* Creates new users based on information they provide
*/
public function signupAction(Request $request)
{
if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED'))
{
// redirect authenticated users to homepage
return $this->redirect($this->generateUrl('wx_exchange_default_index'));
}
$registration = new Registration();
$form = $this->createForm(new RegistrationType(), $registration, array(
'action' => $this->generateUrl('wx_exchange_signup_create'),
));
return array('form' => $form->createView());
}
The answer I finally found is to only display the form elements that you want:
<form action="/app_dev.php/SignUp/create" method="post" name="registration">
<div id="registration">
<div>
<div id="registration_user">
<div>
{{ form_label(form.user.email) }}
{{ form_widget(form.user.email) }}
</div>
<div>
{{ form_label(form.user.username) }}
{{ form_widget(form.user.username) }}
</div>
<div>
{{ form_label(form.user.password.password) }}
{{ form_widget(form.user.password.password) }}
</div>
</div>
<div>
{{ form_label(form.terms) }}
{{ form_widget(form.terms) }}
</div>
<div>
<button name="registration[Sign Up]" id="registration_Sign Up" type="submit">Sign up</button>
</div>
{{ form_widget(form._token) }}
</div>
</form>
This is documented in the Symfony forms chapter.
Im taking over a project in Symfony 2 (of which I have little knowledge) and am having problems with one of the existing forms. It should be pre-populating the form fields with existing data but is failing to do so. Can anybody give and suggestions as to why it may not be working?
Heres my code:
/**
* #Route("/admin/pressrelease/{id}")
* #Template("ImagineCorporateBundle:Admin:Pressrelease/edit.html.twig")
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getRepository('ImagineCorporateBundle:PressRelease');
$pr = $repo->find($id);
if(!$pr->getDocument())
{
$doc = new Document();
$doc->setType('child');
$doc->setTemplate('child');
$pr->setDocument($doc);
}
$dateHelper = $this->get('helper.datehelper');
$years = $dateHelper->dateRangeAction();
$form = $this->createForm(new PressreleaseType(), array($pr , $years) );
if($this->getRequest()->getMethod() == 'POST')
{
$form->bindRequest($this->getRequest());
if($pr->getDocument())
{
$pr->getDocument()->setType('child');
$pr->getDocument()->setTemplate('child');
$pr->getDocument()->setTitle($pr->getTitle());
}
if($form->isValid())
{
$pr->upload('../web/upload/general/');
$em->persist($pr);
$em->persist($pr->getDocument());
$em->flush();
$pr->index(
$this->get('search.lucene'),
$this->generateUrl(
'imagine_corporate_pressrelease_view',
array('id' => $pr->getId(), 'title' => $pr->getTitle())
)
);
return $this->redirect($this->generateUrl('imagine_corporate_pressrelease_admin'));
}
}
return array('pressrelease' => $pr, 'form' => $form->createView());
}
And the view template:
{% extends "ImagineCorporateBundle:Admin:base.html.twig" %}
{% block heading %}Edit Press Release{% endblock %}
{% block content %}
<p>
Upload Attachment |
New Person
</p>
<form action="" method="post" {{ form_enctype(form) }}>
<div>
{{ form_label(form.title) }}
{{ form_errors(form.title) }}
{{ form_widget(form.title) }}
</div>
<div>
{{ form_label(form.author) }}
{{ form_errors(form.author) }}
{{ form_widget(form.author) }}
</div>
<div>
{{ form_label(form.postdate) }}
{{ form_errors(form.postdate) }}
{{ form_widget(form.postdate) }}
</div>
<div>
{{ form_label(form.imageUpload) }}
{{ form_errors(form.imageUpload) }}
{{ form_widget(form.imageUpload) }}
</div>
<div>
{{ form_label(form.thumbnailUpload) }}
{{ form_errors(form.thumbnailUpload) }}
{{ form_widget(form.thumbnailUpload) }}
</div>
<fieldset>
<div><input type="checkbox" class="checkallWebsites"> Check all</div>
{{ form_label(form.websites) }}
{{ form_errors(form.websites) }}
{{ form_widget(form.websites) }}
</fieldset>
<fieldset>
<div><input type="checkbox" class="checkallMagazines"> Check all</div>
{{ form_label(form.magazines) }}
{{ form_errors(form.magazines) }}
{{ form_widget(form.magazines) }}
</fieldset>
<fieldset>
<div><input type="checkbox" class="checkallDept"> Check all</div>
{{ form_label(form.department) }}
{{ form_errors(form.department) }}
{{ form_widget(form.department) }}
</fieldset>
<script>
$(function () {
$('.checkallWebsites').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});
$(function () {
$('.checkallMagazines').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});
$(function () {
$('.checkallDept').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});
</script>
{{ form_widget(form) }}
<div id="submit">
<input type="submit" class="addnew-submit" />
</div>
</form>
{% endblock %}
Thanks in advance!
Your issue is this line in your controller:
$form = $this->createForm(new PressreleaseType(), array($pr , $years) );
If your form is based on an entity then you can bind the entity to the form by just passing the object on it's own like so:
$form = $this->createForm(new PressreleaseType(), $pr);
If it's a more complicated form then your array needs to be key value with the form field names as the keys. For example (you may have to substitute the actual field names if they differ as we cannot see your form class):
$form = $this->createForm(
new PressreleaseType(),
array(
'press_release_name' => $pr->getName(),
'years' => $years
)
);
EDIT:
It's possible that both of those values are needed in the constructor of the form class if it has been customised so if the above doesn't help you then please add your form class code.