In Laravel Backpack need to list users with specific role - roles

please check the details below, where I have a Organizations module. Where I can create a organization with a owner with role "organization".
The third input is a dropdown where we need to select the user with role "organization"
protected function addOrganizationFields(){
$this->crud->addFields([
[
'name' => 'name',
'label' => __('Organization Name'),
'type' => 'text',
],
[
'name' => 'billing_information',
'label' => __('Billing Information'),
'type' => 'textarea',
],
[
'name' => 'owner_id',
'label' => __('Organization Owner'),
'type' => 'select2',
'entity' => 'owners_list',
'attribute' => 'name',
'model' => "App\User",
]
]);
}
In the organization module I wrote this code.
public function owners_list(){
return User::whereHas('roles', function($q){
$q->where('name', 'member');
})->get();
}
in the Organization model relationship I wrote this.
But showing the list of all users in the drop-down.
Can anybody please tel me what is to be done.

You can eliminate options from your select2 field using the “options” attribute mentioned in the docs - https://backpackforlaravel.com/docs/4.1/crud-fields
[
'name' => 'owner_id',
'label' => __('Organization Owner'),
'type' => 'select2',
'entity' => 'owners_list',
'attribute' => 'name',
'model' => "App\User",
// add something like this
'options' => (function ($query) {
return $query->whereHas('roles', function($q){
$q->where('name', 'member');
})->get();
}), // force the related options to be a custom query, instead of all(); you can use this to filter the results show in the select
]

Related

How to remove validation lastname from prestashop 1.7.8.3 backoffice

I have a question how to remove validation from LastName inside client address edit. I need to allow numbers inside this field.
I found here thread Prestashop : Remove Lastname Field Rules Validation From B.O, but this solution is not working.
Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin:
Step 1 - file classes/Address.php
'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255],
Change this to isAnything
Step 2 - src\PrestaShopBundle\Form\Admin\Sell\Address/CustomerAddressType.php
Change your code to below code:
line 209: add('last_name', TextType::class, [
'label' => $this->trans('Last name', 'Admin.Global'),
'help' => $genericInvalidCharsMessage,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
'Admin.Notifications.Error',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH]
),
]),
],
])
Now, you are ready to go and check.
Go to the file classes/Address.php file:
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isCustomerName', 'required' => true, 'size' => 32),
to :
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 32),
validate to isAnything.
I think you were modifying in customer class. Please try with Address.php.
Thanks for sharing the files.
I have resolved the case. You need to modify the classes/form/CustomerAddressForm.php
line 229
$isValid &= $this->validateField('lastname', 'isName', $this->translator->trans(
'Invalid name',
[],
'Shop.Forms.Errors'
));
Change to:
$isValid &= $this->validateField('lastname', 'isAnything', $this->translator->trans(
'Invalid name',
[],
'Shop.Forms.Errors'
));
I want to do this good with override. I have an issue with override this class. I have created module to override but it is not working. There is a way to override this without editing core files?
services:
_defaults:
public: true
form.type.customer_address:
class: 'Playdev\PrestaShopBundle\Form\Admin\Sell\Address\CustomCustomerAddressType'
public: true
arguments:
- '#prestashop.adapter.form.choice_provider.country_state_by_id'
- '#=service("prestashop.adapter.legacy.context").getContext().country.id'
- '#router'
tags:
- { name: form.type }
https://ibb.co/VVjnJYr
There is a file class override:
\modules\pd_overridemodule\src\PrestaShopBundle\Form\Admin\Sell\Address\CustomCustomerAddressType.php
https://ibb.co/7QPHrqx
And I have an error when I am inside Edit Address Form Backoffice
Type error: Too few arguments to function PrestaShopBundle\Form\Admin\Sell\Address\CustomerAddressType::__construct(), 0 passed in C:\laragon\www\prestabiolab\vendor\symfony\symfony\src\Symfony\Component\Form\FormRegistry.php on line 92 and exactly 5 expected
[Symfony\Component\Debug\Exception\FatalThrowableError 0]
https://ibb.co/YfwhtKq
I have found a solution
Need to create module and call hookactionCustomerAddressFormBuilderModifier.
public function hookactionCustomerAddressFormBuilderModifier(array $params)
{
/** #var $formBuilder \Symfony\Component\Form */
$formBuilder = $params['form_builder'];
// remove lastname field
$formBuilder->remove('last_name');
// get all fields without removed
$allFields = $formBuilder->all();
// remove all fields
foreach ($allFields as $inputField => $input) {
$formBuilder->remove($inputField);
}
foreach ($allFields as $inputField => $input) {
// normally add fields
$formBuilder->add($input);
// add fields after firstname
if ($inputField == 'first_name') {
$formBuilder->add('last_name', TextType::class, [
'label' => $this->trans('Last name', [], 'Admin.Global'),
'help' => $this->trans(
'Invalid characters:',
[],
'Admin.Notifications.Info'
) . ' ' . TypedRegexValidator::GENERIC_NAME_CHARS,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', [], 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH],
'Admin.Notifications.Error',
),
]),
],
]);
}
}
}
Now I think it works okey with override :)

How to add an entity content programmatically in drupal

Good night: I used to create node programmatically with a code similar to:
use Drupal\node\Entity\Node;
$nodeObj = Node::create([
'type' => 'article',
'title' => 'Programatically created Article',
'body' => "CodeExpertz is contains best Blogs.",
'field_date' => '2017-10-24',
'field_category' => 'Study',
'uid' => 1,
]);
$nodeObj->save(); // Saving the Node object.
$nid = $nodeObj->id(); // Get Nid from the node object.
Print "Node Id is " . $nid;
Now I want to create entities content (no nodes) but I can't find something about this. I tried to adapt the next snippet:
$term = \Drupal\taxonomy\Entity\Term::create([
'vid' => 'test_vocabulary',
'name' => 'My tag',
]);
$term->save();
to this (vehicle is my entity):
$newvehicle = \Drupal\vehicle\Entity\Vehicle::create([
'title' => 'Ferrari'
]);
$newvehicle->save();
The result is the white page of death.
Thanks for your help.
I was able to do it with this code
use Drupal\customModule\Entity\entityCustom;
$entityCustom = entityCustom::create([
'type' => 'custom_entity',
'uid' => 1,
'status' => TRUE,
'promote' => 0,
'created' => time(),
'langcode' => 'en',
'name' => 'NAME',
]);
$entityCustom->save();

How can I edit or extend the error message in laravel5.3?

I want to extend validation setting another field just like that:
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'another_field' => 'validation'
]);
you can make your own validation case by follwing the documentation :)
If you need to change the message only, you can do it by
$messages = [
'required' => 'The :attribute field is required.',
'email' => 'This is a wrong e-mail address message I wrote myself.',
];
$rules = [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'another_field' => 'validation'
];
return Validator::make($input, $rules, $messages);

remove button from CGridView with condition

Hi I have CRUD generated CGridView in yii. I need to add a new button to CGridView rows and hide it if appointment_status(one of CGridView column) value equals 0
This is my code of CGridView,
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'bookings-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
'name',
'email',
'telephone',
'time',
'employee',
'appointment_status',
'client_ip',
'link' => array(
'header' => 'Confirmation',
'type' => 'raw',
'value' => 'CHtml::button("$data->appointment_status",array("onclick"=>"document.location.href=\'".Yii::app()->controller->createUrl("controller/action",array("id"=>$data->id))."\'"))',
'visible'=>$data->appointment_status==1,
),
array(
'class' => 'CButtonColumn',
),
),
));
But all I'm getting is error stating,
Undefined variable: data
It would be great help if someone can look into it.
you can use like this:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'bookings-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
'name',
'email',
'telephone',
'time',
'employee',
'appointment_status',
'client_ip',
'link' => array(
'header' => 'Confirmation',
'type' => 'raw',
'value' => function ($data) {
if ($data->appointment_status == 1) {
return CHtml::button("$data->appointment_status", array("onclick" => "document.location.href=\'" . Yii::app()->controller->createUrl("controller/action", array("id" => $data->id)) . "\'"));
} else {
return;
}
}
),
array(
'class' => 'CButtonColumn',
),
),
));
Your 'visible' handling the column visibility and not the button, you can use custom attribute on model to create and handle the button visibility.
add to your model:
public function getConfirmationButton()
{
if ($data->appointment_status == 1) {
return CHtml::button($this->appointment_status,array("onclick"=>"document.location.href=\'".Yii::app()->controller->createUrl("controller/action",array("id"=>$this->id))."\'"));
} else {
return '';
}
}
and call it in your view:
..........
'link' => array(
'header' => 'Confirmation',
'type' => 'raw',
'value' => '$data->confirmationButton',
),
...........
visible is a boolean or a PHP expression that will be evaluated to give a boolean. During the evaluation $data is assigned to the current item from the dataProvider used. $data doesn't exist outside of the evaluation function evaluateExpression(). As such the implementation should be:
`visible` => '$data->appointment_status == 1',
You need to quote value of visible key in link array. So instead of this:
'visible'=>$data->appointment_status==1
It should be:
'visible'=>'$data->appointment_status==1'
it should work now.
You will get undefined variable because visible not allow any callback.
Try this solution, it's yii2 code and i don't know much of Yii.
'delete' => function ($url, $model) {
return ($model->isVisible($model)) ?
Html::a('<span class="glyphicon glyphicon-trash"></span>',
$url,
['title' => Yii::t('app', 'Delete')]) : '';
public static function isVisible($data)
{
return ($data->appointment_status == 1) ? true : false;
}

Change imageUrl with user_status field in user table

I have to model: User, UserFlag
In User/index added a column in CGridView:
array(
'class' => 'CButtonColumn',
'htmlOptions' => array("style" => 'width: 45px;'),
'template' => '{enable}',
'header' => 'management',
'buttons' => array(
'enable' => array(
'name' => 'enable',
'imageUrl' => Yii::app()->baseUrl."/images/ico/group.png",
'url' => '"#".$data->username',
'click' => 'js:function() {
if(confirm("Are you sure?")){
changeUserStatus($(this).attr("href").replace("#", ""));
}
}',
),
),
I will read user status from UserFlag Model and if status is active I show 1.png and if status is deactive I show 2.png.
Yeah, the $data var isn't accessible from imageUrl unfortunately. I would recommend extending from CButtonColumn like Stu's link suggested.
If you don't want to do that you could create two button columns and show them depending on the status. It would be something like this but you may need to adjust it if your active user_status value isn't 1 or you want the images reversed:
'enable' => array(
'name' => 'enable',
'visible'=>'$data->user_status == 1'
'imageUrl' => Yii::app()->baseUrl."/images/ico/1.png",
'url' => '"#".$data->username',
'click' => 'js:function() {
if(confirm("Are you sure?")){
changeUserStatus($(this).attr("href").replace("#", ""));
}
}',
),
'disable' => array(
'name' => 'disable',
'visible'=>'$data->user_status == 0'
'imageUrl' => Yii::app()->baseUrl."/images/ico/0.png",
'url' => '"#".$data->username',
'click' => 'js:function() {
if(confirm("Are you sure?")){
changeUserStatus($(this).attr("href").replace("#", ""));
}
}',
),
You would also need to add {disable} to your CButtonColumn template.
It's not ideal since you're repeating code, but at least you can do it without having to extend any classes.