How to change the Filter Value in Drupal Views Query Alter For Paragraph value in Drupal8? - view

My View
Check This Image First
My Filter
Hello all I am trying to change this highlight field value using hook_views_query_alter....but I am unable to do... Can Someone Help me on this Query Alteration I am writing this code but it's not working
foreach ($query->where as &$condition_group) {
foreach ($condition_group['conditions'] as &$condition) {
if ($condition['field'] == 'paragraphs_item_field_data_node__field_recommendation_tagging__paragraph__field_recommendation_tag.field_recommendation_tag_target_id') {
$condition = [
'value' => $rec_tags,
'operator' => 'in',
];
}
}
}

First of all do you enter in your condition?
Verify the fieldname :
paragraphs_item_field_data_node__field_recommendation_tagging__paragraph__field_recommendation_tag.field_recommendation_tag_target_id
If you enter in your condition don't forget to re-add you field in your condition and that your value correspond to the right id :
foreach ($query->where as $condition_group) {
foreach ($condition_group['conditions'] as $condition) {
if ($condition['field'] === $field_name ) {
$condition = [
'field' => $field_name,
'value' => $rec_tags,
'operator' => 'in',
];
}
}
}

Related

Laravel array key validation

I have custom request data:
{
"data": {
"checkThisKeyForExists": [
{
"value": "Array key Validation"
}
]
}
}
And this validation rules:
$rules = [
'data' => ['required','array'],
'data.*' => ['exists:table,id']
];
How I can validate array key using Laravel?
maybe it will helpful for you
$rules = ([
'name' => 'required|string', //your field
'children.*.name' => 'required|string', //your 1st nested field
'children.*.children.*.name => 'required|string' //your 2nd nested field
]);
The right way
This isn't possible in Laravel out of the box, but you can add a new validation rule to validate array keys:
php artisan make:rule KeysIn
The rule should look roughly like the following:
class KeysIn implements Rule
{
public function __construct(protected array $values)
{
}
public function message(): string
{
return ':attribute contains invalid fields';
}
public function passes($attribute, $value): bool
{
// Swap keys with their values in our field list, so we
// get ['foo' => 0, 'bar' => 1] instead of ['foo', 'bar']
$allowedKeys = array_flip($this->values);
// Compare the value's array *keys* with the flipped fields
$unknownKeys = array_diff_key($value, $allowedKeys);
// The validation only passes if there are no unknown keys
return count($unknownKeys) === 0;
}
}
You can use this rule like so:
$rules = [
'data' => ['required','array', new KeysIn(['foo', 'bar'])],
'data.*' => ['exists:table,id']
];
The quick way
If you only need to do this once, you can do it the quick-and-dirty way, too:
$rules = [
'data' => [
'required',
'array',
fn(attribute, $value, $fail) => count(array_diff_key($value, $array_flip([
'foo',
'bar'
]))) > 0 ? $fail("{$attribute} contains invalid fields") : null
],
'data.*' => ['exists:table,id']
];
I think this is what you are looking:
$rules = [
'data.checkThisKeyForExists.value' => ['exists:table,id']
];

How to exclude a perticular field from unique validation in edit mode in cakephp3.0 validation

I want to validate a field called survey_id which is an input from user for uniqueness. It is working properly and giving the correct response when adding the new record, but when I tried to edit this record it is giving an error [unique] => Provided value already exist. So what I want is to exclude the survey_id of the current record from uniqueness check and if user input some other value for survey_id it should check for uniqueness search.
Currently I am using the CakePHP 3.0 validation with on create validation. Here is the validation rule that I am using:
validator
->requirePresence('survey_id', __('msg_required'))
->notEmpty('survey_id', __('msg_required'))
->maxlength('survey_id', 32, __('msg_maxlength'))
->add('survey_id', 'unique', ['rule' => ['validateUnique',['id']], 'provider' => 'table', 'message' => 'Provided value already exist', 'on'=>'create']);
return $validator;
Is there anything wrong with this code?
Thanks in advance.
`
It will work with this validation rule
$validator
->requirePresence('survey_id', __('msg_required'))
->notEmpty('survey_id', __('msg_required'))
->maxlength('survey_id', 32, __('msg_maxlength'))
->alphaNumeric('survey_id', __('msg_surveyid_format'))
->add('survey_id', 'custom', [
'rule' => function ($value, $context) {
if (!empty($context['data']['projectId'])) { $values = array($context['data']['projectId']); } else { $values = array(); }
$data = $this->getSurveyId($value, $values);
return (!empty($data)) ? false : true;
},
'message' => __('msg_surveyid_exsist')]);
return $validator;
}
public function getSurveyId($surveyId = null, $exclude = null) {
$where = array('p.survey_id' => $surveyId);
if (!empty($exclude) && is_array($exclude)) {
$where[] = array('p.id NOT IN' => $exclude);
}
return $this->db->newQuery()
->select('*')
->from(['p' => 'projects'])
->where($where)
->execute()
->fetch('assoc');
}

How to use random_score in yii2 elastic search when working with dataprovider

How can i add random_score in dataprovider search query?
I am using yii2-elastic search extension.
https://github.com/yiisoft/yii2-elasticsearch
First of all you have to set all fields in attributes() including the random_score field.
And then Try this way.
$UserDetail = User::find();
if($this->search != '')
{
$query = $UserDetail->query($condition);
}
else
{
$query = $UserDetail;
}
$provider = new ActiveDataProvider([ 'query' => $UserDetail, 'pagination' => [ 'pageSize' => 10, ] ]);
return $provider;

Empty POST string inserting as zero in MySQL even though column is set to NULL

I have a problem where my database column is set to NULL
`max_vol` MEDIUMINT UNSIGNED NULL,
and my $_POST['max_vol[]'] is an empty string ('') right up to the point of inserting or updating the row in the database (tested output with print_r()). It then inserts 0 (zero) instead of NULL.
If I explicitly set max_vol to NULL it then works.
$value['max_vol'] = empty($value['max_vol']) ? NULL : $value['max_vol'];
but why does this happen? I thought setting an empty string to MySQL (with NULL set) inserted NULL. Here is my original code. Is this something CodeIgniter's query builder changes?
$position_form_data = array(); // positions form data store
// process the form data into arrays for database operations
foreach( $_POST as $post_key=>$post_value ) {
// ignore non-array post variables
if( is_array( $post_value ) ) {
foreach( $post_value as $form_key=>$form_value ) {
if (!isset($position_form_data[$form_key])) {
$position_form_data[$form_key] = array();
}
$position_form_data[$form_key][$post_key] = $form_value;
}
}
}
// if id exists db->update else db->insert
foreach($position_form_data as $value){
// $value['max_vol'] = empty($value['max_vol']) ? NULL : $value['max_vol'];
// data for insert and replace db operations
$data = array(
'id' => $value['id'],
'day' => $_POST['day'],
'title' => $value['title'],
'description' => $value['description'],
'max_vol' => $value['max_vol'],
'is_draft' => $is_draft,
'project_id' => $_POST['project_id']
);
//print_r($data);exit();
if( empty($value['id']) ) {
$this->db->insert('positions', $data);
} else {
$this->db->replace('positions', $data);
}
Thanks.
I can't see any mistake, I can only recommend you try this:
if( ! isset($value['max_vol'])){
if( is_null($value['max_vol'])){
$_max_vol = NULL;
}
else{
$_max_vol = NULL
}
}
else{
$_max_vol = $value['max_vol'];
}
$data = array(
'id' => $value['id'],
'day' => $_POST['day'],
'title' => $value['title'],
'description' => $value['description'],
'max_vol' => $_max_vol,
'is_draft' => $is_draft,
'project_id' => $_POST['project_id']
);

In CakePHP3 how do I create a custom model rule which validates that a time is after another time in the same table?

Columns (both datatype time):
Start
End
End cannot be before start.
$validator
->requirePresence('end', 'create')
->notEmpty('end')
->add('end', [
'time' => [
'rule' => 'time',
'message' => 'end can only accept times.'
],
'dependency' => [
'rule' => [$this, 'endBeforeStart'],
'message' => 'end can not be before start.'
],
]);
If it is a PUT request which only contains end, the model will need to query the existing record to compare against start. If it is a PUT which contains both then it need to validate against the intended new parameter.
How does cakePHP3 do this?
private function endBeforeStart($fieldValueToBeValidated, $dataRelatedToTheValidationProcess)
{
//What goes here?
}
I can't seem to find any examples of doing this online.
I'm not quite sure and haven't tested it, but maybe this gives you some hints:
$validator
->add('end', [
'endBeforeStart' => [
'rule' => function ($value, $context) {
// If it's a POST (new entry):
if ( $context['newRecord'] == '1' ) {
// Do your comparison here
// Input values are e.g. in $context['data']['starttime']
// If end is before start:
return false;
}
// If it's a PUT (update):
else {
// If starttime is not in $context['data']['starttime']
// check for the old value in $getOldEntry
$getOldEntry = $this->getOldEntry( $context['data']['id'] );
// And do your comparison here...
// If end is before start:
return false;
}
return true;
},
'message' => 'end can not be before start.' ],
])
public function getOldEntry($id = null) {
return $this->get($id);
}
I'm also not sure if the last function has to be private or public...

Resources