Symfony form with ChoiceType conditional - html

I want to create a form in symfony with a double checkbox, in mode You approve the privacy policy or you don't approve the privacy policy.
[]I approve the privacy policy [] I do not approve the privacy policy
The doubt that arises is that one of them will be marked dynamically only if the answer to a query is a value a or another (For example a boolean) (So I think it should be relational), in plan: 1 to approve and 0 to not approve, but previously made the query to generate the form.
What I currently have is the following:
$form = $this->createFormBuilder()
->add('LOPD', ChoiceType::class, [
'multiple' => false,
'expanded' => true,
'choices' => [
"Approve the privacy policy" => "0",
"Do not approve privacy policy" => "1",
],
'data' => '1'
])
Then, I don't know how to configure so that the default value, when loading the form, is taken from the User entity. In other words, if the query to user returns a 1, the default option is 0, and the other way around with 0.
I have searched that you can make a query with query_builder, but it is not clear to me how to put the query to do that:
->add('client', EntityType::class, [
'class' => 'App\Entity\User',
'expanded' => true,
'multiple' => false,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
//->where('u.First_Name', ':uid')
//->setParameter('uid', $this->getUser()->getId())
->orderBy('u.id', 'DESC');
},
/*'choice_label' => 'First_Name',*/
'choice_label' => 'tipo',
'choice_value' => 'id'])
How can I do it?

Related

define access role to all user (user,guest,admin,..) in yii2

I use rbac (dektrium) and ACF to check to access users in my project (yii2). I created some role for example :admin, manager, suser,user,.. I have some actions that all user can use its for example view action. how can define in behaviors method that all user can use view action?
To do this we assigned actions to user '*' in yii1.
...
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('view'),
'users'=>array('*'),
),
...
in yii2 use this code ()
...
[
'allow' => true,
'actions' => ['view'],
'roles' => ['?'],
],
...
but when admin user or manager user want to access to myController/view shows forbidden. only guests can access to myController/view, how can define a role or access to access to all user by default?
If you want to allow everyone to access action then there is no need to apply access filter for that action. To avoid applying access filter for specific actions you can use $except property of yii\filters\AccessControl. For example like this:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'except' => ['view'],
'rules' => [
//rules for other actions ...
]
],
//other behaviors ...
];
}
Other option would be to use a combination of roles ? (guests) and # (all logged in users) like this:
[
'allow' => true,
'actions' => ['view'],
'roles' => ['?', '#'],
]
There is also $only property in yii\filters\AccessControl that allows to apply filter only to explicitly named actions. But it's better to use $except for security reasons.
Resources:
yii\filters\AccessControl
yii\filters\AccessRule::$roles

How to set separate homeUrl for authenticated users and guests in yii2

I'm wondering is it possible to make different homeUrl for authenticated and guest users? I have such rules in SiteController.php
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
'denyCallback' => function() {
return $this->redirect('/account');
}
],
[
'actions' => ['logout', 'condition'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
That shouldn't be much of a problem. My answer is structured as follows:
Config for guest users
Config for logged in users (overwriting)
Alternatives
1. Config for guest users
This one is easy. Simply set the home URL to whatever you want your guest visitors to land on. Put this in your config:
//...
'homeUrl'=>'site/home-guests',
//...
2. Config for logged in users (overwriting)
A login happens on each and every page-load either via form submission, cookie (remember me), session or access token. You won't notice this since it happens automatically except for the actual form-login.
The yii\web\User-class has an event which will be triggered after every login. Its called yii\web\User::EVENT_AFTER_LOGIN. You can find the doc for the triggering method here.
To fulfill your requirement simply extend the user class and within the init()-method attach an event handler. If the event mentioned gets thrown, change the home URL. Done!
Heres the code of the custom user class:
class User extends \yii\web\User {
//...
public function init() {
parent::init();
//listen to after login event
$this->on(static::EVENT_AFTER_LOGIN, function ($event) {
Yii::$app->setHomeUrl(Url::to(['site/home-logged-in']));
});
}
//...
}
For Yii to use your custom and extended class, simply tell it to within the config:
//...
'user'=>[
'class'=>'app\components\User',
],
//...
3. Alternatives
If it's not about the URL but simply to show the users different contents depending on their login-status you have other / easier options:
show a different view when logged in but use the same action
redirect them within the action method
if/else within the actual home-view
Which one is right depends on your detailed requirement. This is difficult to tell with the information you provided.
Tell me if you have further questions. I'll be happy to help!

What is best way to redirect on login page in yii2

If user is not logged in then user should have to be redirect on login page, for that i found function which is working fine for me, i used below function
public function beforeAction($action)
{
if (\Yii::$app->getUser()->isGuest &&
\Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
) {
\Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl);
}
return parent::beforeAction($action);
}
This is working fine for me, but for this i need to add function in every controller, what i want to do, i need common function where can i perform this action, So can anyone please tell me what is best way to do this ?
You need to add below code in config/web.php after components part.
'as beforeRequest' => [ //if guest user access site so, redirect to login page.
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
Actually if user does not have rights Yii redirects him to login page by it self.
You can change loginUrl if you have another one. Or you can implement own redirect if for example you use ajax.
http://www.yiiframework.com/doc-2.0/yii-web-user.html
Here is explanation of Yii security
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html

Yii2 create user friendly URL with parameters

Hi I've to create user friendly URL but when using with parameters it's not working.
Url:
Url::to(['site/index', 'id' => 1]);
url looks like :
localhost/testApplication/frontend/web/index.php/site/index?id=1
/forntend/config/main.php
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
//'showScriptName' => false,
'rules' => [
],
],
I want a output like
localhost/testApplication/frontend/web/index.php/site/index/id/1
and after that how to access id value in controller.
'rules' => [
'site/index/id/<id:\d+>' => 'site/index'
//'site/index/<id:\d+>' => 'site/index' Better solution
//'<controller>/<action>/<id:\d+>' => '<controller>/<action>' Will be applied for all controllers and actions
],
Routing Doc.
And after in your action :
public function actionIndex($id)
{
...
}
Is really strange, for me using the parameter 'id' always show errors, I needed to change the parameter to 'user_id', but in other parts of the code I could use, really don't know why, but try to rename the parameter.

Changing selected option in HTML::Form

I am working on an automated form submit script. It is logging in to a vendor's website and populating the fields of a form. When trying to submit, the desired result would be a ticket number displayed, which is acknowledging the form is submitted and the request is processed by their helpdesk.
However the form is not submitted correctly (no acknowledgement is displayed) and I suspect that it is caused by one of the inputs which is a SELECT.
Here is the code I use to set this field:
$forms[3]->value('ProductList','-2');
This has no effect on the the prepared form unfortunately, dumping $forms[3], i see this:
[...]
bless({
'onchange' => ' checkKC(document.all.ProductList, \'~0\'); prodExpand();',
'current' => 1,
'menu' => [
{
'seen' => 1,
'value' => '~0',
'name' => '<Please select>'
},
{
'seen' => 1,
'value' => '-2',
'name' => 'Product not found.... Search more'
},
{
'value' => '-1',
'name' => '------------------------------------'
},
{
'value' => 'Product1',
'name' => 'Product 1 Name'
}
],
'name' => 'ProductList',
'id' => 'ProductList',
'idx' => 1,
'type' => 'option'
}, 'HTML::Form::ListInput' ),
[...]
Am I using the right method of $forms[3]? (it was created by HTML::Form->parse($pageresult) btw) Or is there any other method I should try? I can't find any documentation for HTML::Form::ListInput
Thanks for any advice
Consider using WWW::Mechanize for form processing that takes more than one step. That way you can include the login process in your script along with going to the form and of course getting the result.
Or if you need to work with JavaScript, then use WWW::Mechanize::Firefox.