The parameter must be defined - symfony

I store the keys Stripe in the parameters.yml.dist file, I have the following error message : The parameter "public_key" must be defined.
public function paiementAction(Request $request)
{
if ($request->isMethod('POST')) {
$token = $request->get('stripeToken');
\Stripe\Stripe::setApiKey($this->getParameter("private_key"));
\Stripe\Charge::create(array(
"amount" => 1000,
"currency" => "eur",
"source" => $token,
"description" => "First test charge!"
));
$request->getSession()->getFlashBag()->add('info', 'Paiement accepté');
}
return $this->render('saya25LouvreBundle:Ticket:paiement.html.twig', array(
'public_key' => $this->getParameter("public_key"),
));
}
Vue :
<form action="{{ path('saya25_louvre_paiement') }}" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ public_key }}"
data-amount="1000"
data-name="paiement"
data-description="test"
data-image="http://www.france-hotel-guide.com/fr/blog/wp-content/uploads/2014/09/musee-louvre.jpg"
data-locale="auto"
data-zip-code="true">
</script>
</form>

check if the public_key is correctly configured in the parameters.yml.dist and that you have launch the composer install command from the CLI (so the files parameters.yml will be updated):
>composer install
Hope this help

Related

(Symfony 4) Adding the filepond class wipes out my file widget and nothing shows up on the back end

I want to use filepond to make my input forms fancier, but it replaces my file widget with a series of elements of which have no name attribute, so nothing shows up on the back end.
Here is my Symfony form class:
class UserProfileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName', TextType::class)
->add('lastName', TextType::class)
etc...
// This is the widget I am concerned about for this question
->add('idFile', FileType::class, [
'label' => 'File or Files',
'required' => false,
'mapped' => false,
'multiple' => false
])
etc...
->add('save', SubmitType::class, [
'attr' => ['class' => 'save'],
]);
}
}
Here is what it looks like when I create the file widget in twig:
<div class="col-12">
<label for="file-upload" class="mb-2">Photo I.D.</label>
<!-- so right here where I add the filepond class -->
{{ form_widget(form.idFile, { 'id': 'file-upload', 'attr': {'class': 'form-control filepond'} } ) }}
</div>
Here are the filepond libraries I used, included at the bottom of my twig file:
<!-- Load FilePond library -->
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
<!-- <script src="https://unpkg.com/jquery-filepond/filepond.jquery.js">
</script> -->
<script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.js"></script>
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
<link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css" rel="stylesheet">
So when the twig file loads, filepond takes over and converts my widget to a series of elements with all kinds of properties to them.
That's fine, I understand that filepond does this to fancy up your forms. But the problem is that on the back-end, nothing shows up.
One more thing to add - none of the elements which filepond creates have a "name" attribute to them, I don't understand why.
So when I look at the files suplerglobal on the back end, my idFile is not there.
Just to re-affirm, when I take out the filepond class, my idFile shows back up in the files suplerglobal at the back-end just fine.
Here is the twig-generated input element:
<div class="col-12">
<label for="file-upload" class="mb-2">Photo I.D.</label>
<input type="file" id="file-upload" name="user_profile[idFile]" class="form-control filepond" />
</div>
If I do an inspect element, among the filepond-generated divs there is a < input type="hidden" name="user_profile[idFile]" value="">
Here is the controller code at the back end:
public function saveProfileCompleteAction(Request $request)
{
$user = $this->getUser();
$form = $this->createForm(UserProfileType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$idFile = $form['idFile']->getData();
If I do a dump($idFile); then it just displays null, and I have checked and made sure that I have selected a file to upload.
How can I use the filepond library and get my file input widget to show up on the back-end?

Laravel 5.7 , login redirectes back to login

Im using laravel 5.7, I implemented login using make-auth().
also folowing is my login funtion:
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
$validator = Validator::make($request->all(), [
'email' => 'required|unique:users|max:255',
'password' => 'required',
]);
$credentials= ['email' => $request->get('email'), 'password'=>$request->get('password')];
if (Auth::guard('web')->attempt($credentials)) {
$user = Auth::user();
return redirect(route('home'));
}
$validator->errors()->add('login', 'Invalid Credentials');
return redirect()->back()
->with('loginError','Invalid Credentials')
->withInput($request->only('email', 'remember'));
}
When I try login, the page get redirected back to the login page.
Am I missing out something or is there anything to be added in middleware or any other file
I suspect this part might be the issue?
$validator = Validator::make($request->all(), [
'email' => 'required|unique:users|max:255',
'password' => 'required',
]);
By adding a unique validation rule to the login page (as opposed to the registration page), an existing user would be redirected back with a validation error every time because their email is already in the database.
Check your login page and make sure you're displaying form validation errors. If you see an error stating that the email must be unique, then this is the cause.
Here's a snippet you can use to display errors (from https://laravel.com/docs/5.7/validation#quick-displaying-the-validation-errors)
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Routing in laravel to update the registry

I am trying to update a record but when passing the data, it throws me this error:
MethodNotAllowedHttpException in RouteCollection.php line 218:
I understand that there are problems with routing but I'm unable to find what is causing this.
My form:
<form action="{{route('profesorControll.update', $datosProfesor->id)}}" method="POST">
My routing:
Route::resource('profesorControll', 'profesor\ProfesorController');
My controller:
public function update(Request $request, $id){
$camposProfesor = array('nombre_profesor' => $request['nombre_profesor'], 'apellido_profesor' => $request['apellido_profesor'], 'documento_profesor' => $request['documento_profesor'], 'fecha_nacimiento_profesor' => $request['fecha_nacimiento_profesor'], 'telefono_profesor' => $request['telefono_profesor'], 'telefono_movil_profesor' => $request['telefono_movil_profesor'], 'correo_profesor' => $request['correo_profesor'], 'domicilio_profesor' => $request['domicilio_profesor'], 'institucion_id' => $request['idInstitucion']);
$update = DB::table('profesor')->where('id', $id)->update($camposProfesor);
Session::flash('mensaje_profesor', 'Profesor modificado correctamente');
return redirect('Profesores/Editar/'. $id);
}
How do I solve this problem?
in resource update method is called using the put method to use put method in your form add below
<form action="{{route('profesorControll.update', $datosProfesor->id)}}" method="POST">
{{ method_field('PUT') }}
check here
https://laravel.com/docs/5.3/routing#form-method-spoofing

Generate pdf with knp snappy bundle symfony2

I am a begginer and I want to generate pdf from a twig view. I installed knpsnappy and then I don't really know how to do it. I created a new controller where I put what is told on github.
app/config/config.yml
knp_snappy:
pdf:
enabled: true
binary: "\"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe\""
options: []
image:
enabled: true
binary: "\"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltoimage.exe\""
options: []
I added correctly this line in my AppKernel:
new Knp\Bundle\SnappyBundle\KnpSnappyBundle(),
SA\UserBundle\Controller\PdfController
<?php
namespace SA\UserBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PdfController extends Controller
{
public function generateAction()
{
$html = $this->renderView('FOSUserBundle:Profile:show.html.twig',
array('form' => $form->createView(),
));
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="dossiercandidat.pdf"'
)
);
}
}
Resources\config\routing.yml
user_folder:
defaults: { _controller: SAUserBundle:Pdf:generate }
path: /profile
and I added this line in my twig:
src\SA\UserBundle\Resources\views\Profile\show.html.twig
<form action=" {{ path('user_folder') }} "><input type="submit" value="PDF" onClick=" {{ path('user_folder') }} "></form>
There isn't errors but when I click on the button of course, it doesn't work. Maybe I didn't understand properly how to use the bundle. I need your help!
Your controller and config looks ok. Try testing the PDF generation using a link instead of a form:
Click
And check app/dev.log or app/prod.log depending what environment you are using
The goal is to have an other view which contain the content of your var.
A pdf is generally come with content in database. So you have to take the content of you user, and create a second view call 'content_user.html.twig' in which you include the content of your user and you do the generation of this view.
Your controller :
<?php
namespace SA\UserBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PdfController extends Controller
{
public function generateAction()
{
$html = $this->renderView('FOSUserBundle:Profile:content_user.html.twig',
array('user' => $this->getUser(),
));
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="dossiercandidat.pdf"'
)
);
}
}
And in content_user.html.twig, you manage your data in twig:
Username : {{user.username}}
Firstname: {{user.firstname}}

Why getMethod() returns "GET" instead of "POST"?

The goal is to submit a POST form with two radiobuttons (tipo) and a text field (numero) to make a query in my DB and show the data to the user.
I am trying to submit the form below, however when I submit the form, the request coming accross is a 'GET REQUEST'. The form is in "SupuestoConfig.html.twig":
<div id="cuadro">
<form id="configurador" action="{{ path('configsup') }}" method="POST">
<p class="titulo_configurador">Elija supuesto penal:</p>
{{ form_row(form.tipo) }}
{{ form_row(form.numero, { 'label' : ' ', 'attr' : { 'class' : 'rec3' }}) }}
{{ form_rest(form) }}
<input type="submit" name="cargar" value="Cargar" class="inputbt"/>
</form>
</div>
I render the previous form in "principal.html.twig":
{{ render(controller('PprsBundle:Default:SupuestoConfig'), {'strategy': 'inline'}) }}
My "Controller.php":
/**
* #Route("/pprs/principal/supuesto={numero_supuesto}", name="configsup")
* #Template("PprsBundle:Default:SupuestoConfig.html.twig")
*/
public function SupuestoConfigAction($numero_supuesto = null)
{
$form = $this->createFormBuilder(null)
->add('tipo', 'choice', array(
'choices' => array(
'aleatorio' => 'Aleatorio',
'pornumero' => 'Por número'),
'multiple' => false,
'expanded' => true,
'data' => 'aleatorio'
))
// This add may contains error
->add('numero', 'text', array('label' => ' ','disabled' => true))
->getForm();
$peticion = $this->getRequest();
echo ('<script type="text/javascript">alert ("'.$peticion->getMethod().'");</script>');// Returns 'GET'
if ($peticion->isMethod('POST')) {
// Symfony2.2
$form->bind($peticion);
**$datos = $form->getData();**
*//foreach(array_keys($datos) as $p) {
//echo ('<script type="text/javascript">alert ("'.$datos.'");</script>');
//}*
if ($form->isValid()) { ... }
In Controller.php, despite I´ve got a GET request (when I remove the line
->add('numero', 'text',..
I´ve got a POST request, why is that?), in getData I don´t get the text field.
Finally, my routing.yml:
pprs_principal:
pattern: /pprs/principal/supuesto={numero_supuesto}/
defaults: { _controller: PprsBundle:Default:principal, numero_supuesto: 1 }
_pprs_principal:
pattern: /pprs/principal/
defaults: { _controller: FrameworkBundle:Redirect:redirect, route: pprs_principal }
Sorry for my bad english, Thanks in advance
Edit:
1) Anybody knows why I obtain a GET request instead of a POST when I add the text field in my createFormBuilder?
2) Anybody knows why Don't I get the text field when I call getData?
Help me please...
Maybe this answer could help you out:
getRequest() returns "GET" when posting form
Basically, when rendering a form with a {% render %} tag, it actually creates "another" request... It doesn't pass in the locale, the method, etc.
I opened a bug about this, and it went as By Design:
https://github.com/symfony/symfony/issues/7551

Resources