Modify form value after submit in symfony2 - php

I have form like this :
name (required).
slug (required).
slug is required in back end but user is allowed to leave it blank in form field ( if user leave slug blank, it will use name as the input instead ).
I have tried with Event form listener but it said You cannot change value of submitted form. I tried with Data transformers like this :
public function reverseTransform($slug)
{
if ($slug) {
return $slug;
} else {
return $this->builder->get('name')->getData();
}
}
return $this->builder->get('name')->getData(); always return null. So I tried like this:
public function reverseTransform($slug)
{
if ($slug) {
return $slug;
} else {
return $_POST['category']['name'];
}
}
it works but I think it against the framework. How I can done this with right way?

You can also do it in the controller
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
// get the data sent from your form
$data = $form->getData();
$slug = $data->getSlug();
// if no slug manually hydrate the $formObject
if(!$slug)
{
$formObject->setSlug($data->getName());
}
$em->persist($formObject);
$em->flush();
return ....
}
}

If you use a function to keep the code at one place then you should also not work with Request data.
In the form action you call that function including the name variable.
public function reverseTransform($name, $slug)
{
if (!empty($slug)) {
return $slug;
} else {
return $name;
}
}

Another possible way is to set via request class like this:
Array form <input name="tag['slug']"...>:
public function createAction(Request $request)
{
$postData = $request->request->get('tag');
$slug = ($postData['slug']) ? $postData['slug'] : $postData['name'];
$request->request->set('tag', array_merge($postData,['slug' => $slug]));
.......
Common form <input name="slug"...>:
$request->request->set('slug', 'your value');
I think this is the best way because if you are using dml-filter-bundle you don't need to filter your input in your controller like this again:
$this->get('dms.filter')->filterEntity($entity);

Related

laravel-admin + laravel 5.5 save 2 field with same value

I have a form that needs to generate slug, I use laravel-admin by z-song.
link: https://github.com/z-song/laravel-admin/
In documentation, a form can simply like this:
protected function form()
{
$form = new Form(new Post);
$form->text('title');
$form->hidden('slug');
return $form;
}
buts it's both manual input. that's not what I need since slug needs to be auto-generated.
I am trying do like this:
protected function form()
{
$form = new Form(new Post);
$form->text('title', 'Title');
$form->hidden('slug')->value(str_slug($form->title));
return $form;
}
buts its result NULL for the slug one.
so how to make it happen?
Laravel admin has some callbacks on $form, that can be useful for generating slug case :
use Illuminate\Support\Str;
$form->text('title');
$form->hidden('slug');
$form->saving(function (Form $form) {
$form->slug = Str::slug($form->title);
});
Note : You can read more about Laravel Helpers, ex. Str::slug.

Sending POST request with GET parameter in Laravel

For example, I have this route in my web.php :-
Route::get('products/{product}/owners', 'ProductController#showOwners');
When I try to add new 'Owner' to the product, I have to do it in the parent URL, like this :-
Route::post('products/storeOwner', 'ProductController#storeOwner');
And then I pass the product ID in a hidden field in the form, because the post request doesn't accept URL parameters. So is there anyway to do it like below ?
Route::post('products/{product}/storeOwner', 'ProductController#storeOwner');
So the POST request will be sent inside the particular 'product' URL?
UPDATE
/* ProductController Class */
public function storeOwner (AddProductOwner $request)
{
$product= Product::find($request->product);
$user = Auth::user();
if ( $user->ownerOf($product)) {
// Check if the current user is already one of the owners).
// If the current user is the owner then return to the product
// This line is not executed because in (products/show.blade.php) we have set a condition.
return redirect('products/' . $request->product);
}
$join = new Join;
$join->role = $request->join_role;
$join->product()->associate($request->product);
$join->user()->associate(Auth::user());
$join->message = $request->message;
$join->save();
// TODO: we have to make this with ajax instead of normal form
return redirect('products/'. $request->product);
}
I hope my question is clear enough..
Yes you can do as you mentioned in your last route
Route::post('products/{product}/storeOwner', 'ProductController#storeOwner');
And then get the product Id in your functions argument
public function storeOwner (AddProductOwner $request, $productId)
{
dd($productId); // TRY THIS OUT. CHECK THE 2nd ARGUMENT I SET.
$product= Product::find($productId); // PASS THE VERIABLE HERE.
$user = Auth::user();
if ( $user->ownerOf($product)) {
// Check if the current user is already one of the owners).
// If the current user is the owner then return to the product
// This line is not executed because in (products/show.blade.php) we have set a condition.
return redirect('products/' . $request->product);
}
$join = new Join;
$join->role = $request->join_role;
$join->product()->associate($request->product);
$join->user()->associate(Auth::user());
$join->message = $request->message;
$join->save();
// TODO: we have to make this with ajax instead of normal form
return redirect('products/'. $request->product);
}
You can send URL parameters to a POST request. Just make sure in your form you are sending the wildcard.
<form action="/products/{{ $productid }}/storeOwner" method="POST">
In your routes
Route::post('products/{productid}/storeOwner', 'ProductController#storeOwner');
In your controller, use it
public function storeOwner($productid)
{
dd($productid);
}

Laravel how to validate request class but not in method parameter

Here is my case, I got a Request Class which I create using artisan :
php artisan make:request StoreSomethingRequest
Then I put my rules there, and then I can use it in my Controller method like this:
public function store(StoreSomethingRequest $request)
{
}
But what I need is, I want to separate 2 Request logic based on the button in my view (Assumes there is more than 1 submit button in my view). So my controller will look like this :
public function store(Request $request)
{
if($request->submit_button === 'button1')
{
// I want to validate using StoreSomethingRequest here
}
else
{
// I dont want to validate anything here
}
}
I would appreciate any suggestion / help. Please. :D
You can use something like this in your request class inside rules method.
public function rules()
{
$rules = [
'common_parameter_1' => 'rule:rule',
'common_parameter_2' => 'rule:rule',
];
if($this->submit_button === 'button1')
{
$rules['custom_parameter_for_button_1'] = 'rule:rule';
}
else
{
$rules['custom_parameter_for_button_2'] = 'rule:rule';
}
return $rules;
}
Add name and value attributes on the HTML submit buttons. Then check which one has been submitted. Example:
<button type="submit" name="action" value="button1">Save 1</button>
<button type="submit" name="action" value="button2">Save 2</button>
Then in the handler:
If (Request::input('action') === 'button1') {
//do action 1
} else {
// do action 2
}

Yii2, custom validation: clientValidateAttribute() doesn't work correctly

I have form, created by ActiveForm widget. User enters polish postal code there. In appropriate controller I put entered data in DB, for example:
$company_profile_data->postal_code = $_POST['CompanyProfiles']['postal_code'];
$company_profile_data->update();
I decided to use standalone validator for postal code validation. Rules for this attribute in model:
public function rules() {
return [
//...some other rules...
['postal_code', 'string', 'length' => [6,6]],
['postal_code', PostalValidator::className()], //standalone validator
];
}
app/components/validators/PostalValidator class code:
namespace app\components\validators;
use yii\validators\Validator;
use app\models\CompanyProfiles;
use app\models\Users;
class PostalValidator extends Validator {
public function init() {
parent::init();
}
public function validateAttribute($model, $attribute) {
if (!preg_match('/^[0-9]{2}-[0-9]{3}$/', $model->$attribute))
$model->addError($attribute, 'Wrong postal code format.');
}
public function clientValidateAttribute($model, $attribute, $view) { //want js-validation too
$message = 'Invalid status input.';
return <<<JS
if (!/^[0-9]{2}-[0-9]{3}$/.test("{$model->$attribute}")) {
messages.push("$message");
}
JS;
}
}
So, an example of correct code is 00-202.
When I (in user role) enter incorrect value, page reloads and I see Wrong postal code format. message, although I redefined clientValidateAttribute method and wrote JS-validation, which, as I suggested, will not allow page to reload. Then I press submit button again: this time page doesn't reload and I see Invalid status input. message (so, the second press time JS triggers). But I when enter correct code after that, I still see Invalid status input. message and nothing happens.
So, what's wrong with my clientValidateAttribute() method? validateAttribute() works great.
UPDATE
Snippet from controller
public function actionProfile(){ //can't use massive assignment here, cause info from 2 (not 1) user models is needed
if (\Yii::$app->user->isGuest) {
return $this->redirect('/site/index/');
}
$is_user_admin = Users::findOne(['is_admin' => 1]);
if ($is_user_admin->id == \Yii::$app->user->id)
return $this->redirect('/admin/login/');
$is_user_blocked = Users::find()->where(['is_blocked' => 1, 'id' => \Yii::$app->user->id])->one();
if($is_user_blocked)
return $this->actionLogout();
//3 model instances to retrieve data from users && company_profiles && logo
$user_data = Users::find()->where(['id'=>\Yii::$app->user->id])->one();
$user_data->scenario = 'update';
$company_profile_data = CompanyProfiles::find()->where(['user_id'=>Yii::$app->user->id])->one();
$logo = LogoData::findOne(['user_id' => \Yii::$app->user->id]);
$logo_name = $logo->logo_name; //will be NULL, if user have never uploaded logo. In this case placeholder will be used
$upload_logo = new UploadLogo();
if (Yii::$app->request->isPost) {
$upload_logo->imageFile = UploadedFile::getInstance($upload_logo, 'imageFile');
if ($upload_logo->imageFile) { //1st part ($logo_data->imageFile) - whether user have uploaded logo
$logo_file_name = md5($user_data->id);
$is_uploaded = $upload_logo->upload($logo_file_name);
if ($is_uploaded) { //this cond is needed, cause validation for image fails (?)
//create record in 'logo_data' tbl, deleting previous
if ($logo_name) {
$logo->delete();
} else { //if upload logo first time, set val to $logo_name. Otherwise NULL val will pass to 'profile' view, and user wont see his new logo at once
$logo_name = $logo_file_name.'.'.$upload_logo->imageFile->extension;
}
$logo_data = new LogoData;
$logo_data->user_id = \Yii::$app->user->id;
$logo_data->logo_name = $logo_name;
$logo_data->save();
}
}
}
if (isset($_POST['CompanyProfiles'])){
$company_profile_data->firm_data = $_POST['CompanyProfiles']['firm_data'];
$company_profile_data->company_name = $_POST['CompanyProfiles']['company_name'];
$company_profile_data->regon = $_POST['CompanyProfiles']['regon'];
$company_profile_data->pesel = $_POST['CompanyProfiles']['pesel'];
$company_profile_data->postal_code = $_POST['CompanyProfiles']['postal_code'];
$company_profile_data->nip = $_POST['CompanyProfiles']['nip'];
$company_profile_data->country = $_POST['CompanyProfiles']['country'];
$company_profile_data->city = $_POST['CompanyProfiles']['city'];
$company_profile_data->address = $_POST['CompanyProfiles']['address'];
$company_profile_data->telephone_num = $_POST['CompanyProfiles']['telephone_num'];
$company_profile_data->email = $_POST['CompanyProfiles']['email'];
$company_profile_data->update();
}
if (isset($_POST['personal-data-button'])) {
$user_data->username = $_POST['Users']['username'];
$user_data->password_repeat = $user_data->password = md5($_POST['Users']['password']);
$user_data->update();
}
return $this->render('profile', ['user_data' => $user_data, 'company_profile_data' => $company_profile_data, 'upload_logo' => $upload_logo, 'logo_name' => $logo_name]);
}
My inaccuracy was in clientValidateAttribute() method. Instead of $model->$attribute in code snippet:
if (!/^[0-9]{2}-[0-9]{3}$/.test("{$model->$attribute}")) {
...I had to use predefined JS-var value, cause this var changes with entered value change. So, my new code is:
public function clientValidateAttribute($model, $attribute, $view) {
return <<<JS
if (!/^[0-9]{2}-[0-9]{3}$/.test(value)) {
messages.push("Wrong postal code format.");
}
JS;
}
Model does not load rules and behaviors until not called any function from model. When you call $company_profile_data->update(); model call update and validate functions.
Try add after $company_profile_data = CompanyProfiles::find() this code:
$company_profile_data->validate();
Or just use load function. I think it will help.

How to enable hiddenField in Yii Framework?

I am using a Yii hiddenField in a CActiveForm widget. I have saved this hidden field value in database. There is no issue with storing in DB with Controller action at all. after saving this the hidden field should display the value. And how can I populate the form with the database stored value. Or how to refer some other field in the form to contain value from DB after save is processed.
<?php echo $form->hiddenField($model,'ad_form_id',array('value'=>$base)); ?>
My controller action
public function actionBCFormFields()
{
$model=new BCFormField();
if(isset($_POST['BCFormField']))
{
$model->ad_form_id = $_POST['BCFormField']['ad_form_id'];
$model->attributes=$_POST['BCFormField'];
if ($model->save()){
echo'saved';
}
$this->redirect(array('create',
'crm_base_form_field_id'=>$model->crm_base_form_field_id));
}
Based on the very litle code you have given us i would suggest something like this in your controller, but if you edit your question and elaborate , i will edit my question:
public $ad_form_id
public function actionCreate()
{
$model = new User;
$this->ad_form_id = $this->base;
if (isset($_POST['User'])) {
$model->attributes = $_POST['User'];
$this->base = $this->ad_form_id;
if ($model->validate() && $model->save()) {
$this->redirect(array('view'));
}
}
$this->render('create',array('model' => $model,));
}

Categories