How to access $_POST in Twig form? - php

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.

Related

How to write Controller in GRAV CMS

I created a form and want to save submitted data in back-end
//front-end
{% extends 'partials/base.html.twig' %}
{% block content %}
<form method="post" action="savedata">
<input type=text name="data">
<input type="submit">
</form>
{% endblock %}
//back-end
function savedata()
{
echo 'saved data:'.$_POST['data'];
exit;
}
I expect the code like this
$grav->post('/savedata', DataController->savedata);
But I cannot found any tutorial about custom Controller in documentation
How can I achieve this purpose?

How to submit a form using PUT http verb in Laravel

I know that this question may have been made but I just can't get it to work. if someone could help me I would be very grateful. I have colletive/form installed but the answer can be an html form tag too.
Now listing my form, my route and my exception.
{{ Form::model( array('route' => array('casas.update', 238), 'method' => 'PUT')) }}
<input type="hidden" name="_method" value="PUT">
-
Route::resource('casas', 'CasasController');
exception:
MethodNotAllowedHttpException in RouteCollection.php line 218:
With plain html / blade
<form action="{{ route('casas.update', $casa->id) }}" method="post">
{{ csrf_field() }}
{{ method_field('put') }}
{{-- Your form fields go here --}}
<input type="submit" value="Update">
</form>
Wirth Laravel Collective it may look like
{{ Form::model($casa, ['route' => ['casas.update', $casa->id], 'method' => 'put']) }}
{{-- Your form fields go here --}}
{{ Form::submit('Update') }}
{{ Form::close() }}
In both cases it's assumed that you pass a model instance $casa into your blade template
In your controller
class CasasController extends Controller
{
public function edit(Casa $casa) // type hint your Model
{
return view('casas.edit')
->with('casa', $casa);
}
public function update(Request $request, Casa $casa) // type hint your Model
{
dd($casa, $request->all());
}
}

Using same view for editing and viewing symfony

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.

Symfony2 Customize the Form from the Simple Registration Tutorial

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.

Symfony 2 form not pre-populating with pre-saved data

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.

Categories