How can I connect my application with the database....? - symfony-2.5

I have tried too many times to connect my symfony application with the database but I didn't get any output from it.Here I have shown the whole MVC code.I need insert and select for it.
Following is my Entity file.
namespace Atpl\FrontBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TblSignup
*
* #ORM\Table(name="tbl_signup")
* #ORM\Entity
*/
class TblSignup
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="fname", type="string", length=255, nullable=false)
*/
private $fname;
/**
* #var string
*
* #ORM\Column(name="lname", type="string", length=255, nullable=false)
*/
private $lname;
/**
* #var string
*
* #ORM\Column(name="company_name", type="string", length=255, nullable=false)
*/
private $companyName;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, nullable=false)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="web_url", type="string", length=255, nullable=false)
*/
private $webUrl;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=20, nullable=false)
*/
private $phone;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=50, nullable=false)
*/
private $password;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fname
*
* #param string $fname
* #return TblSignup
*/
public function setFname($fname)
{
$this->fname = $fname;
return $this;
}
/**
* Get fname
*
* #return string
*/
public function getFname()
{
return $this->fname;
}
/**
* Set lname
*
* #param string $lname
* #return TblSignup
*/
public function setLname($lname)
{
$this->lname = $lname;
return $this;
}
/**
* Get lname
*
* #return string
*/
public function getLname()
{
return $this->lname;
}
/**
* Set companyName
*
* #param string $companyName
* #return TblSignup
*/
public function setCompanyName($companyName)
{
$this->companyName = $companyName;
return $this;
}
/**
* Get companyName
*
* #return string
*/
public function getCompanyName()
{
return $this->companyName;
}
/**
* Set email
*
* #param string $email
* #return TblSignup
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set webUrl
*
* #param string $webUrl
* #return TblSignup
*/
public function setWebUrl($webUrl)
{
$this->webUrl = $webUrl;
return $this;
}
/**
* Get webUrl
*
* #return string
*/
public function getWebUrl()
{
return $this->webUrl;
}
/**
* Set phone
*
* #param string $phone
* #return TblSignup
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set password
*
* #param string $password
* #return TblSignup
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
}
Here is my Controller( DefaultController.php) file.
/**
* #Route("/",name="atpl_front_signup")
* #Template()
* #return type
*/
public function signUpAction(Request $request)
{
$entity = new TblSignup();
$form = $this->createForm($entity);
$form->handleRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('atpl_signup_create', array('id'=>$entity->getId())));
}
return array('entity'=>$entity,'form'=>$form->createView());
}
My twig file contains several blocks from which I need to insert data and need to display the data in the database.
{% block section_signup %}
<section id="signup">
<form method="POST" id="signupform" action="{{path('atpl_signup_create')}}">
<div class="signup-body">
<div class="container">
<div class="col-md-12">
<div class="col-md-6 block">
<h1>Sign Up Now</h1>
<h4><font><img src="{{asset('bundles/wpapp/images/user-icon.png')}}"></font><font>Your Contact Information</font></h4>
<div class="tr">
<label>First Name</label>
<input type="text" name="fname" id="fname">
</div>
<div class="tr">
<label>Last Name</label>
<input type="text" name="lname" id="lname">
</div>
<div class="tr">
<label>Company Name</label>
<input type="text" name="compName" id="compName">
</div>
<div class="tr">
<label>Email</label>
<input type="text" name="email" id="email">
</div>
<div class="tr">
<label>Confirm Email</label>
<input type="text" name="confEmail" id="confEmail">
</div>
<div class="tr">
<label>Website URL</label>
<input type="text" name="webUrl" id="webUrl">
</div>
<div class="tr">
<label>Phone</label>
<input type="text" name="phone" id="phone">
</div>
<div class="tr">
<label>Password</label>
<input type="password" name="password" id="password">
</div>
<div class="tr">
<label>Confirm Password</label>
<input type="password" name="confPass" id="confPass">
</div>
<div class="tr">
<input type="checkbox" class="check">
<label class="label2">Click Here to Automatically Remember Your Password on This Computer</label>
</div>
<div class="tr text-center">
<font>(click only once and allow time to process)</font>
<input type="submit" class="btn" value="Create Account">
</div>
</div>
<div class="col-md-6 block">
<div class="moneyback">
<div class="inn">
<div class="icon"><img src="{{asset('bundles/wpapp/images/money-icon.png')}}"></div>
<div class="text">
<h3>MONEY BACK GUARANTEE</h3>
</div>
</div>
</div>
<div class="text-center">
<img src="{{asset('bundles/wpapp/images/icon1.png')}}">
<img src="{{asset('bundles/wpapp/images/icon2.png')}}">
<img src="{{asset('bundles/wpapp/images/icon3.png')}}">
Privacy Policy
</div>
</div>
</div>
</div>
</div>
</form>
<div class="page-scroll arrow2">
</div>
</section>
{% endblock %}

I didn't read all the code, but your code can't work if in your controller you don't have all the "use" necessary: I leave you with the documentation : http://symfony.com/fr/doc/current/book/doctrine.html

Related

laravel 5.4 Form doesn't show anything on localhost. and it also shows no any error message. It's blank

Description:
I downloaded and installed Form from https://laravelcollective.com/docs/5.4/html and configure all files as per instructions.
Collective\Html\HtmlServiceProvider::class,
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
Problem:
My Route http://127.0.0.1:8000/admin/product/create is showing a blank page. In actual it should show me a Form.
There is no any error message in all code or localhost.
HTML CODE:
#extends('admin.layout.admin')
#section('content')
<h3>Add Product</h3>
<div class="row">
<div class="col-md-8 col-md-offset-2">
{!! Form::open(['route' => 'product.store', 'method' => 'POST', 'files' => true, 'data-parsley-validate'=>'']) !!}
<div class="form-group">
{{ Form::label('name', 'Name') }}
{{ Form::text('name', null, array('class' => 'form-control','required'=>'','minlength'=>'5')) }}
</div>
<div class="form-group">
{{ Form::label('description', 'Description') }}
{{ Form::text('description', null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('price', 'Price') }}
{{ Form::text('price', null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('size', 'Size') }}
{{ Form::select('size', [ 'small' => 'Small', 'medium' => 'Medium','large'=>'Large'], null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
{{ Form::label('category_id', 'Categories') }}
{{ Form::select('category_id', $categories, null, ['class' => 'form-control','placeholder'=>'Select Category']) }}
</div>
<div class="form-group">
{{ Form::label('image', 'Image') }}
{{ Form::file('image',array('class' => 'form-control')) }}
</div>
{{ Form::submit('Create', array('class' => 'btn btn-default')) }}
{!! Form::close() !!}
</div>
</div>
#endsection
product.php code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable=['name','description','size','category_id','image','price'];
public function category()
{
return $this->belongsTo(Category::class);
}
public function images()
{
return $this->hasMany(ProductImage::class);
}
public function reviews()
{
return $this->hasMany(ProductReview::class);
}
public function getStarRating()
{
$count = $this->reviews()->count();
if(empty($count)){
return 0;
}
$starCountSum=$this->reviews()->sum('rating');
$average=$starCountSum/ $count;
return $average;
}
}
ProductsController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Your create() is empty,so it will not show anything. It should be like this
public function create()
{
return view('form');
}
form is name on your view.

TYPO3 action does not call

I have TYPO3 7.6.18 and I have the problem, that my addCommentAction does not work/does not get called.
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerPlugin(
"MyVendor.".$_EXTKEY,
'commentForm',
'Comment form'
);
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'MyVendor.'.$_EXTKEY,
'commentForm',
array('Comment' => 'form,addComment'),
array('Comment' => 'form,addComment')
);
<f:form action="addComment" object="{newComment}" name="newComment" method="post" additionalParams="{showUid: userto}">
<div style="overflow: hidden;">
<div id="reviewStars-input">
<f:form.hidden property="userto" value="{userto}"/>
<f:form.radio property="rating" value="5" id="star-4"/>
<label title="{f:translate(key: 'tx_fecomments_domain_model_comment.gorgeous')}" for="star-4"></label>
<f:form.radio property="rating" value="4" id="star-3"/>
<label title="{f:translate(key: 'tx_fecomments_domain_model_comment.good')}" for="star-3"></label>
<f:form.radio property="rating" value="3" id="star-2"/>
<label title="{f:translate(key: 'tx_fecomments_domain_model_comment.regular')}" for="star-2"></label>
<f:form.radio property="rating" value="2" id="star-1"/>
<label title="{f:translate(key: 'tx_fecomments_domain_model_comment.poor')}" for="star-1"></label>
<f:form.radio property="rating" value="1" id="star-0"/>
<label title="{f:translate(key: 'tx_fecomments_domain_model_comment.bad')}" for="star-0"></label>
</div>
</div>
<div>
<f:form.textfield style="height: 100px;" property="text"/>
<br>
<f:form.submit class="btn btn-primary" value="{f:translate(key: 'tx_fecomments_domain_model_comment.send_comment')}"/>
</div>
</f:form>
/**
* #param \MyVendor\Fecomments\Domain\Model\Comment $newComment
* #return bool
*/
public function addCommentAction(\MyVendor\Fecomments\Domain\Model\Comment $newComment)
{
die(8979);
}
When I click "send form" nothing happens. I don't know why. Seems addComment action does not get called. In my other extension similar code works properly. When I click "send form" I have the next url site.en/?showUid=1&tx_fecomments_commentform%5Baction%5D=addComment&tx_fecomments_commentform%5Bcontroller%5D=Comment&cHash=236d87f2ee987ddf7b5720ae5ddc029e
It must work, so I don't know why it does not works. Help me please, I really don't have any ideas.
Also it's my Comment model:
namespace MyVendor\Fecomments\Domain\Model;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
class Comment extends AbstractEntity {
/**
* #var string
**/
protected $text = '';
/**
* user
*
* #var \Fhk\Feusersplus\Domain\Model\User
*/
protected $userfrom;
/**
* user
*
* #var \Fhk\Feusersplus\Domain\Model\User
*/
protected $userto;
/**
* #var int
**/
protected $crdate;
/**
* #var int
**/
protected $rating;
/**
* #param int $userfrom
*/
public function setUserfrom($userfrom) {
$this->userfrom = (int)$userfrom;
}
/**
* #return \Fhk\Feusersplus\Domain\Model\User
*/
public function getUserfrom() {
return $this->userfrom;
}
/**
* #param int $userto
*/
public function setUserto($userto) {
$this->userto = (int)$userto;
}
/**
* #return \Fhk\Feusersplus\Domain\Model\User
*/
public function getUserto() {
return $this->userto;
}
/**
* #param int $crdate
*/
public function setCrdate($crdate) {
$this->userto = (int)$crdate;
}
/**
* #param int $rating
*/
public function setRating($rating) {
$this->rating = (int)$rating;
}
/**
* #return int
*/
public function getCrdate() {
return $this->crdate;
}
/**
* #return int
*/
public function getRating() {
return $this->rating;
}
/**
* #param $text
*/
public function setText($text) {
$this->text = (string)$text;
}
/**
* #return string
*/
public function getText() {
return $this->text;
}
}
I solved my problem. Field 'rating' was not defined on my TCA.

Redirection into blank page laravel 5.4

I have a problem here in my Laravel 5.4 project multi-auth system. The problem is Laravel redirects me to a blank page, let's say instead of admin/home it redirects me to a blank page has URI /admin
here is my migrations first is admin.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('adress');
$table->string('email')->unique();
$table->string('password');
$table->integer('cin')->unique()->unsigned();
$table->integer('phone')->unique()->unsigned();
$table->string('sexe');
$table->boolean('activation')->default(0);
$table->string('token',254)->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
And here is the admin model implementation:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\notifications\AdminResetPasswordNotification;
class Admin extends Authenticatable
{
use Notifiable;
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new AdminResetPasswordNotification($token));
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name' , 'last_name' , 'adress', 'email' , 'password' , 'cin' , 'phone' , 'sexe', 'activation'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roleUser(){
return $this->hasOne('App\RoleUser');
}
public function salary(){
return $this->hasOne('App\Salary');
}
public function images()
{
return $this->morphMany('App\Image','imageable');
}
public function subjects()
{
return $this->hasMany('App\Subject');
}
public function documents()
{
return $this->hasMany('App\Document');
}
}
Third here is roleuser migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoleUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('role_users', function (Blueprint $table) {
$table->increments('id');
$table->integer('admin_id')->unsigned()->index();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('role_users');
}
}
RoleUser MODEL
namespace App;
use Illuminate\Database\Eloquent\Model;
class RoleUser extends Model
{
protected $fillable = [
'name' , 'admin_id'
];
public function admin(){
return $this->belongsTo('App\Admin');
}
}
So I duplicate the auth folder views in admin folder in views and I changed actions.
#extends('layouts.subhome')
#section('content')
#include('includes.wow')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Login sfdsgf</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('admin.login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('admin.password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div><br>
<br>
<br>
<br>
<br>
<br>
#endsection
Here is the login controller:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = 'admin/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
//$this->middleware('guest:admin', ['except' => 'logout']);
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
foreach ($this->guard()->user()->roleUser() as $role) {
if ($role->name == 'Amministratore') {
return redirect('admin/home');
}elseif($role->name == 'Avocate') {
return redirect('avocate/home');
}elseif($role->name == 'Reddattore Professionale') {
return redirect('reddattoreprofessionale/home');
}elseif($role->name == 'Reddattore Apprendista') {
return redirect('reddattoreapprendista/home');
}elseif($role->name == 'Segretario') {
return redirect('segretario/home');
}else{
return redirect('/');
}
}
}
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('admin.login');
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('admin');
}
}
This is the list of routes:
<?php
Route::get('/', function () {
return view('welcome');
})->name('welcome');
Route::get('/subscribe', function () {
return view('admSubscribe');
})->name('adminsub');
Route::GET('/sottoscrizione/lavoro', 'AdminController#index');
Route::RESOURCE('/sottoscrizione/lavoro', 'AdminController');
Auth::routes();
Route::GET('/home', 'HomeController#index');
Route::GET('admin/home','AdminController#showHome')->name('admin.home');
Route::GET('avocate/home','AvocatController#showHome')->name('avocat.home');
Route::GET('reddattoreprofessionale/home','ProfessionalRedactorController#showHome')->name('redpro.home');
Route::GET('reddattoreapprendista/home','TrainerRedactorController#showHome')->name('redtrain.home');
Route::GET('segretario/home','SecretaryController#showHome')->name('segretario.home');
Route::GET('admin','Admin\LoginController#showLoginForm')->name('admin.login');
Route::POST('admin','Admin\LoginController#login');
Route::POST('admin-password/email','Admin\ForgotPasswordController#sendResetLinkEmail')->name('admin.password.email');
Route::GET('admin-password/reset','Admin\ForgotPasswordController#showLinkRequestForm')->name('admin.password.request');
Route::POST('admin-password/reset','Admin\ResetPasswordController#reset');
Route::GET('admin-password/reset/{token}','Admin\ResetPasswordController#showResetForm')->name('admin.password.reset');
Ok please help, I've been stuck here for 4 weeks in this problem.

symfony2 Form Collections: adding new item to collection from a pre populated list

I'm building a basic fantasy football game as a base for learning symfony2 and doctrine.
i have an the following entities:
Contest - holds various contests that can be entered
Player - holds details on players that can be selected for the
contest
ContestEntry: holds a contest Entry comprising of contestID, UserID and
selection of players.
I'm currently building the player selection page.
I have a controller that gets a list of available players for selection, which is rendered as a table, each row has a button, i will use javascript so that when the selection button is clicked it will add the player to the form collection and then save the player in my ManyToMany table, when the form is submitted.
New players cannot be added or deleted they can only be selected from the list of available players.
The main page for the contest entry:
{% extends '#Design/Default/layout-main.html.twig' %}
{% block title %}Enter Contest{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link href="{{ asset('bundles/design/css/homebase.css') }}" type="text/css" rel="stylesheet"/>
<link href="{{ asset('bundles/design/css/menu.css') }}" type="text/css" rel="stylesheet"/>
<link href="{{ asset('bundles/design/css/bootstrap.css') }}" rel="stylesheet"/>
{% endblock %}
{% block header %}
{% include 'DesignBundle:Default/Menus:homepage-menu.html.twig' %}
<div class="row">
{% if app.session.flashBag.has('success') %}
<div class="alert alert-success">
×
{% for msg in app.session.flashBag.get('success') %}
{{ msg }}
{% endfor %}
</div>
{% endif %}
</div>
<section>
<div class="container">
<div class="row jumbotron color-bkg">
{% include 'GameBundle:Contest/Partial:contest_details.html.partial.twig' %}
<div class="row">
<div class="col-md-6">
<div class="row centered-form">
{{ contest.contestID }}
{{ render(controller('GameBundle:FantasyPlayer:getPlayers', {'contestID': contest.contestID})) }}
</div>
</div>
<div class="col-md-6">
Select Your Team!!
Need to render the contestEntry Form here with the ability to add a player when a player from the list is clicked
In addition each added player will have a remove button to remove the player from the team.
</div>
</div>
</div>
</div>
</div>
</section>
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script type="text/javascript">
</script>
{% endblock %}
The controller that gets the list of players available for selection:
class FantasyPlayerController extends Controller
{
public function getPlayersAction($contestID)
{
$em = $this->get('doctrine.orm.entity_manager');
//get the repos
$contestRepo = $em->getRepository('GameBundle:Contest');
$scheduleGroupRepo = $em->getRepository('GameBundle:ScheduleGroup');
$playerRepo = $em->getRepository('DataBundle:DailyFantasyPlayer');
$contest = $contestRepo->find($contestID);
//var_dump($contest);die();
//get the ScheduleGroup
$scheduleGroup = $contest->getScheduleGroup();
//var_dump($scheduleGroup);die();
//get schedules
$schedules = $scheduleGroupRepo->getScheduleGroup($scheduleGroup);
//var_dump($schedules);die();
//get teams playing in schedules
$teamsArray = array();
foreach($schedules as $schedule){
$hometeam = $schedule->getHomeTeam();
$awayteam = $schedule->getAwayTeam();
array_push($teamsArray, $hometeam);
array_push($teamsArray, $awayteam);
}
//Get players matching the teams
$dfp = $playerRepo->getAvaliablePlayersByTeam($teamsArray);
return $this->render('GameBundle:Forms:player-list.html.twig', array(
'dfp' => $dfp
));
}
The Twig Tempate for the playerlist:
<table class="table table-condensed">
<thead>
<tr>
<th>Position</th>
<th>Player</th>
<th>Opp</th>
<th>Opp Rank</th>
<th>FPPG</th>
<th>Salary</th>
<th></th>
</tr>
</thead>
<tbody>
{% for p in dfp %}
<tr id="player-{{ p.playerID }}" data-player="{'position':'{{ p.position }}', 'salary': '{{ p.salary }}', 'pid': '{{ p.playerID }}'">
<td>{{ p.position }}</td>
<td>{{ p.name }}</td>
<td>{{ p.team }} # {{ p.opponent }}</td>
<td>{{ p.opponentRank }}</td>
<td>{{ p.opponentPositionRank }}</td>
<td>{{ p.salary }}</td>
<td>
<div class="btn btn-sm btn-default player-select">Select</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
The controller is called in my twig template for entering the contest.
My ContestEntry entity has the ManyToMany Defined (its unidirectional as i only need to get players that have been assigned to a contest entry)
/**
* ContestEntry
*
* #ORM\Table(name="fp_contestEntry")
* #ORM\Entity(repositoryClass="FantasyPro\GameBundle\Entity\ContestEntryRepository")
*/
class ContestEntry
{
public function __construct()
{
$this->user = new ArrayCollection();
$this->contest = new ArrayCollection();
$this->players = new ArrayCollection();
}
/**
* #var integer
*
* #ORM\Column(type="integer", name="id")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(type="integer", nullable=true, name="user")
*
*/
private $user;
/**
* #var integer
*
*
* #ORM\ManyToOne(targetEntity="FantasyPro\GameBundle\Entity\Contest", inversedBy="contestEntries")
* #ORM\Column(type="integer", nullable=false, name="contest")
*
*/
private $contest;
/**
*
*
* #ORM\ManyToMany(targetEntity="FantasyPro\DataBundle\Entity\Player", inversedBy="contestEntries")
* #ORM\JoinTable(
* name="Player_ContestEntry",
* joinColumns={#ORM\JoinColumn(name="contestEntryID", referencedColumnName="id", nullable=false)},
* inverseJoinColumns={#ORM\JoinColumn(name="playerID", referencedColumnName="playerID", nullable=false)}
* )
*/
private $players;
/**
* #var boolean
*
* #ORM\Column(type="boolean", nullable=true, name="locked")
*/
private $locked;
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #return int
*/
public function getUser()
{
return $this->user;
}
/**
* #param int $user
*/
public function setUser( $user = null )
{
$this->user = $user;
}
/**
* #return int
*/
public function getContest()
{
return $this->contest;
}
/**
* #param int $contest
*/
public function setContest( $contest = null )
{
$this->contest = $contest;
}
/**
* #return int
*/
public function getPlayers()
{
return $this->players;
}
/**
* #param int $players
*/
public function setPlayers( $players = null )
{
$this->players = $players;
}
/**
* #return boolean
*/
public function isLocked()
{
return $this->locked;
}
/**
* #param boolean $locked
*/
public function setLocked( $locked )
{
$this->locked = $locked;
}
}
From other questions i've read here, i need to be using a form collection.
class ContestEntryType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('user', 'hidden')
->add('contest', 'hidden')
->add('locked', 'hidden')
->add('players', 'collection', array(
'type' => 'hidden',
'allow_add' => true)
);
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FantasyPro\GameBundle\Entity\ContestEntry'
));
}
/**
* #return string
*/
public function getName()
{
return 'fantasypro_gamebundle_contestentry';
}
}
Ive read the docs on symfony form collections but am having trouble understanding it, as it does not seem to give any examples of what i'm trying to do, adding a <TR> with the players information, along with a hidden field containing the playerID (to be stored in my ManyToMany Table).
Can anybody give me some pointers in the right direction?

Error on form submission: The CSRF token is invalid. Please try to resubmit the form [duplicate]

This question already has answers here:
The CSRF token is invalid. Please try to resubmit the form
(15 answers)
Closed 7 years ago.
I've been trying to submit a form which adds a Question object into the db.
But everytime I do, the error "The CSRF token is invalid. Please try to resubmit the form" shows up.
On my form's content field, I've attached this plugin which is an editor same as Stack Overflow's.
In my form's tag field, I've attached this one for tag autocompletion.
Here's my controller code:
/**
* Creates a new Question entity.
*
* #Route("/ask", name="question_create")
* #Method("POST")
* #Template("VerySoftAskMeBundle:Question:ask.html.twig")
*/
public function createAction(Request $request) {
$entity = new Question();
$form = $this->createCreateForm($entity);
$tags = $this->getDoctrine()->getRepository('VerySoftAskMeBundle:Tag')->findAll();
date_default_timezone_set('Asia/Manila');
$entity->setDateOfPost(new \DateTime());
$entity->setOwner($this->getUser());
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('question_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
'tags' => $tags
);
}
/**
* Creates a form to create a Question entity.
*
* #param Question $entity The entity
*
* #return Form The form
*/
private function createCreateForm(Question $entity) {
$form = $this->createForm(new QuestionType(), $entity, array(
'action' => $this->generateUrl('question_create'),
'method' => 'POST',
'em' => $this->getDoctrine()->getEntityManager()
));
$form->add('submit', 'submit', array('label' => 'Ask'));
return $form;
}
/**
*
* #Route("/ask", name="ask")
* #Security( "has_role( 'ROLE_USER' )" )
* #Method("GET")
* #Template
*/
public function askAction() {
$tags = $this->getDoctrine()->getRepository('VerySoftAskMeBundle:Tag')->findAll();
$entity = new Question();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
'tags' => $tags
);
}
I've made a Data Transformer for my tag field which turns the input tags into tag objects.
class TagTransFormer implements DataTransformerInterface {
/**
* #var ObjectManager
*/
private $om;
/**
* #param ObjectManager $om
*/
public function __construct(ObjectManager $om) {
$this->om = $om;
}
/**
* Transforms an object (issue) to a string (number).
*
* #return ArrayCollection
*/
public function transform($tags) {
return $tags;
}
/**
* Transforms a string (number) to an object (issue).
*
* #param string $number
*
* #return ArrayCollection
*
* #throws TransformationFailedException if object (issue) is not found.
*/
public function reverseTransform($ids) {
$tags = array();
if (!$ids) {
return null;
}
$repo = $this->om
->getRepository('VerySoftAskMeBundle:Tag');
$idsArray = explode(",", $ids);
foreach ($idsArray as $id) {
$tags[] = $repo->findOneByName($id);
}
return $tags;
}
}
Here's my form class:
class QuestionType extends AbstractType {
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$entityManager = $options['em'];
$transformer = new TagTransFormer($entityManager);
$builder
->add('title', 'text')
->add('content', 'textarea')
->add($builder->create('tags', 'text')
->addModelTransformer($transformer)
);
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'VerySoft\AskMeBundle\Entity\Question'
))
->setRequired(array(
'em',
))
->setAllowedTypes(array(
'em' => 'Doctrine\Common\Persistence\ObjectManager',
));
}
/**
* #return string
*/
public function getName() {
return 'verysoft_askmebundle_question';
}
}
My Twig Template:
<div id="askDiv" style="padding-bottom: 90px;">
{{ form_start(form, { 'attr' : { 'novalidate' : 'novalidate', 'class' : 'col-md-offset-3 form-control-static col-md-7' } }) }}
<div class="col-lg-12" style="padding: 0px; margin-bottom: 30px;">
<span class="askLabels col-lg-1 text-left">{{ form_label(form.title) }}</span>
{{form_widget(form.title, { 'attr' : { 'class' : 'form-control col-lg-11' } })}}
</div>
{{ form_widget(form.content, { 'attr' : { 'class' : 'col-lg-12' } }) }}
<div class="col-lg-12" style="padding: 0px; margin-top: 20px;">
<label class="col-lg-1 text-left askLabels" for="tagField">Tags</label>
<div class="col-lg-8">
{{ form_widget(form.tags) }}
</div>
{% if app.user.reputation >= 100 %}
<a id="addTag" title="Add New Tag" data-toggle="tooltip modal" data-placement="left" class="col-lg-3" href="#"><i class="fa fa-plus-circle"></i></a>
<div id="mymodal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add New Tag</h4>
</div>
<div class="modal-body">
<label for="tagName">Tag Name: </label>
<input id="tagName" class="form-control" type="text"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Add Tag</button>
</div>
</div>
</div>
</div>
{% endif %}
</div>
<div style="margin-top: 20px; ">
{{ form_widget(form.submit, { 'attr' : { 'class' : 'col-md-offset-4 col-md-4 btn btn-primary' } }) }}
</div>
<p>
title error{{ form_errors(form.title) }}
</p>
<p>
content error{{ form_errors(form.content) }}
</p>
<p>
tag error{{ form_errors(form.tags) }}
</p>
<p>
form error{{ form_errors(form) }}
</p>
Scripts:
$(document).ready(function(){
$("textarea").pagedownBootstrap();
var zeTags = ["{{ tags|join('", "')|raw }}"];
$('#verysoft_askmebundle_question_tags').tagit({
availableTags: zeTags,
tagLimit: 5,
beforeTagAdded: function(event, ui) {
if ($.inArray(ui.tagLabel, zeTags) == -1)
return false;
}
});
});
You missed
{{ form_rest(form) }}
Symfony2 has a mechanism that helps to prevent cross-site scripting: they generate a CSRF token that have to be used for form validation. Here, in your example, you're not displaying (so not submitting) it with form_rest(form). Basically form_rest(form) will "render" every field that you didn't render before but that is contained into the form object that you've passed to your view. CSRF token is one of those values.
For newer versions of Symonfy, e.g. 2.4+ you would use the newer form_end(form), which automatically renders all fields not rendered as well as the CSRF token.
Per the documentation:
form_end() - Renders the end tag of the form and any fields that have not yet been rendered. This is useful for rendering hidden fields and taking advantage of the automatic CSRF Protection.