Confirm password field not validating using 'repeated' field using form builder in symfony2 ? - validation

This is how my code snippet looks like.
// --- this is the code in my controller ----
$registrationForm = $this->createFormBuilder()
->add('email')
->add('password', 'repeated', array('type' => 'password', 'invalid_message' => 'Passwords do not match'))
->getForm();
return $this->render('AcmeHelloBundle:Default:index.html.twig', array('form' => $registrationForm->createView()));
// --- This is the twig file code----
<form action="#" method="post" {{ form_enctype(form) }}>
{{ form_errors(form) }}
{{ form_row( form.email, { 'label': 'E-Mail:' } ) }}
{{ form_errors( form.password ) }}
{{ form_row( form.password.first, { 'label': 'Your password:' } ) }}
{{ form_row( form.password.second, { 'label': 'Repeat Password:' } ) }}
{{ form_rest( form ) }}
<input type="submit" value="Register" />
</form>
Can any one suggest why it is not working using form builder?

In Symfony 2, validation is handled by domain object. So you have to pass an Entity (domain object) to your form.
Code in controller :
public function testAction()
{
$registration = new \Acme\DemoBundle\Entity\Registration();
$registrationForm = $this->createFormBuilder($registration)
->add('email')
->add('password', 'repeated', array('type' => 'password', 'invalid_message' => 'Passwords do not match'))
->getForm();
$request = $this->get('request');
if ('POST' == $request->getMethod()) {
$registrationForm->bindRequest($request);
if ($registrationForm->isValid()) {
return new RedirectResponse($this->generateUrl('registration_thanks'));
}
}
return $this->render('AcmeDemoBundle:Demo:test.html.twig', array('form' => $registrationForm->createView()));
}
1) The form builder will map the form fields with the properties of your entity, and hydrate your form field values with your entity property values.
$registrationForm = $this->createFormBuilder($registration)...
2) The bind will hydrate your form fields values with all the data posted
$registrationForm->bindRequest($request);
3 ) To launch validation
$registrationForm->isValid()
4) if the data posted are valid, you have to redirect to an action to inform user that everything is OK, to avoid displaying an alert message from your broswer who ask if your are sure to repost data.
return new RedirectResponse($this->generateUrl('registration_thanks'));
Entity code :
<?php
namespace Acme\DemoBundle\Entity;
class Registration
{
private $email;
private $password;
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
}
doc for validation : http://symfony.com/doc/current/book/validation.html
NOTE : there is no need to add some validation on password entity property, the repeatedType done it for you

Related

Why does the old() method not work in Laravel Blade?

My environment is Laravel 6.0 with PHP 7.3. I want to show the old search value in the text field. However, the old() method is not working. After searching, the old value of the search disappeared. Why isn't the old value displayed? I researched that in most cases, you can use redirect()->withInput() but I don't want to use redirect(). I would prefer to use the view(). method
Controller
class ClientController extends Controller
{
public function index()
{
$clients = Client::orderBy('id', 'asc')->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
public function search()
{
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
$query = Client::query();
if (isset($clientID)) {
$query->where('id', $clientID);
}
if ($status != "default") {
$query->where('status', (int) $status);
}
if (isset($nameKana)) {
$query->where('nameKana', 'LIKE', '%'.$nameKana.'%');
}
if (isset($registerStartDate)) {
$query->whereDate('registerDate', '>=', $registerStartDate);
}
if (isset($registerEndDate)) {
$query->whereDate('registerDate', '<=', $registerEndDate);
}
$clients = $query->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
}
Routes
Route::get('/', 'ClientController#index')->name('client.index');
Route::get('/search', 'ClientController#search')->name('client.search');
You just need to pass the variables back to the view:
In Controller:
public function search(Request $request){
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
...
return view('auth.client.index', compact('clients', 'clientID', 'status', 'nameKana', 'registerStartDate', 'registerEndDate'));
}
Then, in your index, just do an isset() check on the variables:
In index.blade.php:
<input name="clientID" value="{{ isset($clientID) ? $clientID : '' }}"/>
<input name="status" value="{{ isset($status) ? $status : '' }}"/>
<input name="nameKana" value="{{ isset($nameKana) ? $nameKana : '' }}"/>
...
Since you're returning the same view in both functions, but only passing the variables on one of them, you need to use isset() to ensure the variables exist before trying to use them as the value() attribute on your inputs.
Also, make sure you have Request $request in your method, public function search(Request $request){ ... } (see above) so that $request->input() is accessible.
Change the way you load your view and pass in the array as argument.
// Example:
// Create a newarray with new and old data
$dataSet = array (
'clients' => $query->paginate(Client::PAGINATE_NUMBER),
// OLD DATA
'clientID' => $clientID,
'status' => $status,
'nameKana' => $nameKana,
'registerStartDate' => $registerStartDate,
'registerEndDate' => $registerEndDate
);
// sent dataset
return view('auth.client.index', $dataSet);
Then you can access them in your view as variables $registerStartDate but better to check if it exists first using the isset() method.
example <input type='text' value='#if(isset($registerStartDate)) {{registerStartDate}} #endif />

laravel-5.8:The POST method is not supported for this route. Supported methods: GET, HEAD

hi m trying to add products in cart but it says: The POST method is not supported for this route. Supported methods: GET, HEAD.. (View: \resources\views\product\detail.blade.php), I wants that by clicking the addtocart it redirect me to that age with products,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,...…………………………………..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
route:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
view:
<form method="POST" action="{{ route('addToCart') }}" enctype="multipart/form-data">
<div class="btn-addcart-product-detail size9 trans-0-4 m-t-10 m-b-10">
#if($product->product_status == 1)
<!-- Button -->
<button class="flex-c-m sizefull bg1 bo-rad-23 hov1 s-text1 trans-0-4">
Add to Cart
</button>
#else Out Of Stock #endif
</div>
</form>
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
First of all your form method in the view is POST but you don't have a post route.
Second, the route that you have defined expect a parameter(product) you can change the form action as below BUT I think you want to send the user to another page so you can use a link instead of form.
Here's the form action:
action="{{ route('addToCart', $product->id) }}"
And if you want to use link, you can do something like this:
.....
Your method should be POST. In the form, you're calling it Post method but in route.php file, you defined as get to change it as Route::post
Route::post('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
In addition, your route.php file expecting {product} so you need to pass it in form route so your action be like {{ route('addToCart',$product->id) }}
<form method="POST" action="{{ route('addToCart',$product->id) }}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Laravel 5.5 - Save multiple data continiously from blade

I want to make a PHP method using laravel. I want to do the comparison of criteria and criteria. Here is the controller code :
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
return view('kriteria_kriterias.create')->with('kriteria1', $kriteria1)->with('kriteria2', $kriteria2)->with('data', $data);
}
and this is the blade code :
It will make the form appear as total of criteria#
The problem is, I can't save it all to database. How do I get it to do this?
Updated method in the controller to the following:
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
How to output in the blade file:
{{ $kriteria1 }}
{{ $kriteria2 }}
Or you update the controller to pass the complete results:
public function create($id1, $id2)
{
$kriteria1 = Model\Kriteria::find($id1);
$kriteria2 = Model\Kriteria::find($id2);
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
And the in the blade you can accss the data in various ways, one way is a foreach loop using blade in the blade template:
#foreach($kriteria1 as $k1)
{{ $k1 }}
#endforeach
#foreach($kriteria2 as $k2)
{{ $k2 }}
#endforeach'
To accept multiple values dynamicaly in the controller you can try something like this:
public function create($ids)
{
$results = collect([]);
foreach($ids as $id) {
$kriteria = Model\Kriteria::findOrFail($id);
if($kriteria) {
$results->put('kriteria' . $id, $kriteria);
}
}
return view('kriteria_kriterias.create')->with($results);
}
Then use the same looping method mentioned above to display them in the blade or a for loop that gets the count and displays accordingly.
maybe you forgot to add the opening tag ;)
{!! Form::open(array('url' => 'foo/bar')) !!}
//put your code in here (line 1-34)
{!! Form::close() !!}

Yii2 Validate multiple models

I have two models in Yii2 (masterTransaction and splitTransaction), where each masterTransactions can have multiple splitTransactions. Each splitTransaction has an attribute 'amount'. My problem is I need to validate if the sum over all 'amount' attributes is 0.
My first solution was to make another model called Transaction, in which I had an attribute where I saved an instance of the masterTransaction model and another attribute with an array of splitTransaction instances. I did the validation with a custom inline validatior, which work perfectly.
Transaction model
class Transaction extends Model
{
public $masterTransaction;
public $splitTransactions;
public function init()
{
$this->masterTransaction = new MasterTransaction();
$this->splitTransactions[] = new SplitTransaction();
}
public function rules()
{
return [
['splitTransactions', 'validateSplitTransactions'],
];
}
public function validateSplitTransactions($attribute, $params)
{
$sum = 0;
foreach ($this->$attribute as $transaction) {
$sum = bcadd($sum, $transaction->amount, 3);
}
if ($sum != 0) {
$this->addError($attribute, 'The sum of the entries has to be 0');
}
}
public function save()
{
$this->masterTransaction->save();
foreach ($this->splitTransactions as $splitTransaction) {
$splitTransaction->master_transaction_id = $this->masterTransaction->id;
$splitTransaction->save();
}
}
}
Controller function to create the model
public function actionCreate()
{
$transaction = new Transaction();
$count = count(Yii::$app->request->post('SplitTransaction', []));
for ($i = 1; $i < $count; $i++) {
$transaction->splitTransactions[] = new SplitTransaction();
}
if ($transaction->masterTransaction->load(Yii::$app->request->post()) && Model::loadMultiple($transaction->splitTransactions, Yii::$app->request->post())) {
$transaction->masterTransaction->user_id = Yii::$app->user->id;
foreach ($transaction->splitTransactions as $splitTransaction) {
$splitTransaction->user_id = Yii::$app->user->id;
}
if ($transaction->validate()) {
$transaction->save();
}
}
return $this->render('create', [
'transaction' => $transaction,
]);
}
But when I tried building a form to input the data, I ran into a problem with the Ajax validation. The validation would work, but Yii didn't know where to put the error message, so it just deleted it.
I suspect that this is just not the preferred way in Yii2 model my data, but I don't really have another idea. Maybe someone has some ideas for me.
Option 1.
It depends on your view file codes. Does your form contains "splitTransactions" variable? If not, you can put it like this
<?= $form->field($model, 'splitTransactions')->hiddenInput(['maxlength' => true])->label(false); ?>
The variable will be hidden, but still show errors. In some case validation will not be fired because of empty value of "splitTransactions" variable.
"splitTransactions" should contain some value to fire validation. You can put some value to if before pasting the form like this
$model->splitTransactions=1;
Option 2.
You can add error to other variable (which form contains) like this
public function validateSplitTransactions($attribute, $params)
{
$sum = 0;
foreach ($this->$attribute as $transaction) {
$sum = bcadd($sum, $transaction->amount, 3);
}
if ($sum != 0) {
$this->addError('transaction_number', 'The sum of the entries has to be 0');
}
}
Look, form should contain "transaction_number" variable. Error will be added to "transaction_number" input.
Option 3. In my experience.
It is better to separate ajax validation from form action url a.g. create another controller action for ajax validation and use it.
Example
Create model FeedbackForm
class FeedbackForm extends Model
{
public $name;
public $email;
public $text;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['name', 'email', 'text'], 'required'],
[['name', 'email'], 'string', 'max' => 128],
[['email'], 'email'],
[['text'], 'string', 'max' => 512],
];
}
public function attributeLabels()
{
return [
'name' => \Yii::t('front', 'Name'),
'email' => \Yii::t('front', 'Email'),
'text' => \Yii::t('front', 'Message text'),
];
}
}
put actions to SiteSontroller
public function actionFeedback()
{
$model= new \frontend\models\FeedbackForm;
$model->load(Yii::$app->request->post());
if($model->validate()) {
$newFeed=new \frontend\models\Feedback;
$newFeed->create_time=new \yii\db\Expression('NOW()');
$newFeed->name=$model->name;
$newFeed->email=$model->email;
$newFeed->is_new=1;
$newFeed->text=$model->text;
if($newFeed->save()) {
\Yii::$app->session->setFlash('success', \Yii::t('front', 'Your message has accepted'));
} else {
\Yii::$app->session->setFlash('error', \Yii::t('front', 'Error on save'));
}
} else {
\Yii::$app->session->setFlash('error', \Yii::t('front', 'Data error'));
}
return $this->redirect(['/site/index']);
}
public function actionFeedbackvalidate()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model= new \frontend\models\FeedbackForm;
$model->load(Yii::$app->request->post());
return ActiveForm::validate($model);
}
And create form inside view
<?php $model=new \frontend\models\FeedbackForm; ?>
<?php $form = ActiveForm::begin([
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'validationUrl'=>['/site/feedbackvalidate'],
'validateOnSubmit' => true,
'id' => 'form-feedback',
'action'=>['/site/feedback'],
'options'=>['class'=>'some class', 'autocomplete'=>'off']
]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true, 'placeholder'=>$model->getAttributeLabel('name'), 'autocomplete'=>'off'])->label(false); ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true, 'placeholder'=>$model->getAttributeLabel('email'), 'autocomplete'=>'off'])->label(false); ?>
<?= $form->field($model, 'text')->textarea(['maxlength' => true, 'placeholder'=>$model->getAttributeLabel('text'), 'autocomplete'=>'off'])->label(false); ?>
<div class="form-group">
<input type="submit" class="btn btn-default" value="<?php echo Yii::t('front', 'Send') ?>">
</div>
<?php ActiveForm::end(); ?>
That is it

Keeping modal dialog open after validation error laravel

So basically I have a blade.php, controller page and a form request page(validation). I'm trying to keep my modal dialog open if there is an error but I just cant figure it out, what part of code am I missing out on or needs to be changed?
blade.php
<div id="register" class="modal fade" role="dialog">
...
<script type="text/javascript">
if ({{ Input::old('autoOpenModal', 'false') }}) {
//JavaScript code that open up your modal.
$('#register').modal('show');
}
</script>
Controller.php
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function register(StoreNewUserRequest $request)
{
// process the form here
$this->userRepository->upsert($request);
Session::flash('flash_message', 'User successfully added!');
//$input = Input::except('password', 'password_confirm');
//$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
return redirect()->back();
}
}
class UserRepository {
public function upsert($data)
{
// Now we can separate this upsert function here
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}
request.php
class StoreNewUserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
// create the validation rules ------------------------
return [
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the user table
'password' => 'required|min:8|alpha_num',
'password_confirm' => 'required|same:password', // required and has to match the password field
'mobile' => 'required',
'role_id' => 'required'
];
}
}
Laravel automatically checks for errors in the session data and so, an $errors variable is actually always available on all your views. If you want to display a modal when there are any errors present, you can try something like this:
<script type="text/javascript">
#if (count($errors) > 0)
$('#register').modal('show');
#endif
</script>
Put If condition outside from script. This above is not working in my case
#if (count($errors) > 0)
<script type="text/javascript">
$( document ).ready(function() {
$('#exampleModal2').modal('show');
});
</script>
#endif
for possibly multiple modal windows you can expand Thomas Kim's code like following:
<script type="text/javascript">
#if ($errors->has('email_dispatcher')||$errors->has('name_dispatcher')|| ... )
$('#register_dispatcher').modal('show');
#endif
#if ($errors->has('email_driver')||$errors->has('name_driver')|| ... )
$('#register_driver').modal('show');
#endif
...
</script>
where email_dispatcher, name_dispatcher, email_driver, name_driver
are your request names being validated
just replace the name of your modal with "login-modal". To avoid error put it after the jquery file you linked or jquery initialized.
<?php if(count($login_errors)>0) : ?>
<script>
$( document ).ready(function() {
$('#login-modal').modal('show');
});
</script>
<?php endif ?>

Resources