Getting Taxonomy term name from target ID - D9 - drupal

Getting Taxonomy term name from Taxonomy target ID:
I have a taxonomy term that accepts multiple values. It's rendered as a multiselectfield. I am trying to read the target ID of the field and figure the term name out of it using the below code in a preprocess function:
$granttype = $user_entity->field_user_grant_type->getValue();
foreach($granttype as $gt)
{
$granttype_name = \Drupal\taxonomy\Entity\Term::load($gt)->label();
}
dd($granttype_name);
$variables['grant_type'] = $granttype_name;
dd($granttype) shows the below output:
However, the foreach loop to figure out the term name is not working correctly.
dd($granttype_name) results as:
The website encountered an unexpected error. Please try again later.
TypeError: Illegal offset type in Drupal\Core\Entity\EntityStorageBase->load() (line 297 of core/lib/Drupal/Core/Entity/EntityStorageBase.php).
I am looping through the target ID and trying to get the term name. But it's not working. Any help pls?
UPDATE: I tried the below line of code:
$term = term::load($gt);
$name = $term->getName();
still no luck :( same error

Here is an example how to do this:
$grant_type = $user_entity->field_user_grant_type->entity;
if ($grant_type instanceof \Drupal\taxonomy\TermInterface) {
var_dump($grant_type->label());
}
If you have multiple referenced terms, use:
$grant_types = $user_entity->field_user_grant_types->referencedEntities();
foreach ($grant_types as $grant_type) {
var_dump($grant_type->label());
}
Explanation:
The generic way to get entity title is the Entity::label method
$term->label();
There is a helpful method Entity::referencedEntities to get relations.

First, you need to include
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\TermInterface;
Second, retrieve the value(s) stored in your field (field_user_grant_type) and store them in an array:
$myArray = array();
$granttype = $user_entity->get('field_user_grant_type')->getValue();
$granttype will now contain an array of arrays. Next, you need to gather the actual term IDs
foreach($granttype as $type){
$myArray[] = $type['target_id'];
}
Finally, loop through $myArray and fetch the term IDs stored there, and then use each ID to get its corresponding Term Name. Here, I store them in a new array called grantTypeNames
grantTypeNames = array();
foreach($myArray as $term_id){
$grantTypeNames[] = Term::load($term_id)->get('name')->value;
}
The array $grantTypeNames will now contain the term names you want. I hope that helps.

Related

Populating an Apex Map from a SOQL query

// I have a custom metadata object named boatNames__mdt and I'm using two methods to get a list of picklist values in a String[];
First Method
Map<String, boatNames__mdt> mapEd = boatNames__mdt.getAll();
string boatTypes = (string) mapEd.values()[0].BoatPick__c;
// BoatPick__c is a textarea field (Eg: 'Yacht, Sailboat')
string[] btWRAP = new string[]{};
**btWRAP**.addAll(boatTypes.normalizeSpace().split(','));
Second Method
string[] strL = new string[]{};
Schema.DescribeFieldResult dfr = Schema.SObjectType.boatNames__mdt.fields.BoatTypesPicklist__c;
// BoatTypesPicklist__c is a picklist field (Picklist Values: 'Yacht, Sailboat')
PicklistEntry[] picklistValues = dfr.getPicklistValues();
for (PicklistEntry pick : picklistValues){
**strl**.add((string) pick.getLabel());
}
Map with SOQL query
Map<Id, BoatType__c> boatMap = new Map<Id, BoatType__c>
([Select Id, Name from BoatType__c Where Name in :btWRAP]);
When I run the above Map with SOQL query(btWRAP[]) no records show up.
But when I used it using the strl[] records do show up.
I'm stunned!
Can you please explain why two identical String[] when used in exact SOQL queries behave so different?
You are comparing different things so you get different results. Multiple fails here.
mapEd.values()[0].BoatPick__c - this takes 1st element. At random. Are you sure you have only 1 element in there? You might be getting random results, good luck debugging.
normalizeSpace() and trim() - you trim the string but after splitting you don't trim the components. You don't have Sailboat, you have {space}Sailboat
String s = 'Yacht, Sailboat';
List<String> tokens = s.normalizeSpace().split(',');
System.debug(tokens.size()); // "2"
System.debug(tokens); // "(Yacht, Sailboat)", note the extra space
System.debug(tokens[1].charAt(0)); // "32", space's ASCII number
Try splitting by "comma, optionally followed by space/tab/newline/any other whitespace symbol": s.split(',\\s*'); or call normalize in a loop over the split's results?
pick.getLabel() - in code never compare using picklist labels unless you really know what you're doing. Somebody will translate the org to German, French etc and your code will break. Compare to getValue()

How do I pass a filter to Count?

Is it possible to put a filter into the Issue model whose items are getting counted here????
issues = Student.objects.annotate(Count('issue'))
I really need to filter it so as to get the desired outcome...
If not is there a way I can be able to get count of all Issues to a particular student?
class Issue(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE
borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE)
book_id = models.ForeignKey(Books,on_delete=models.CASCADE)
class Student(models.Model):
school = models.ForeignKey(School, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
student_id = models.CharField(max_length=20)
Yes, you can filter what items are counted with the filter=… parameter [Django-doc]. We can for example filter on the book_id with:
issues = Student.objects.annotate(
num_issues=Count(
'issue',
filter=Q(issue__book_id_id=some_book_id)
)
)
or to exclude soft deleted items, we can work with the deleted field that has been defined in your model (by the django-safedelete package):
issues = Student.objects.annotate(
num_issues=Count(
'issue',
filter=Q(issue__deleted=False)
)
)
Note: Normally one does not add a suffix _ids to a ManyToManyField field, since Django
it refers to a manager over the target objects. Therefore it should
be book, instead of book_id.

How to extract a string value from an array using scripted field in kibana?

Is there a way to extract a string value from an array with the use of if statement in scripted field in kibana. I tried the below code, however, I am unable to filter out the correct and incorrect values in discover tab of kibana. This might be due to remark field is an array.
def result_string = "";
if (doc['nac.keyword'].value =="existing_intent" &&doc['remark.keyword'].value != "acceptable") {
result_string = "incorrect";
}
if (doc['nac.keyword'].value =="existing_intent" &&doc['remark.keyword'].value == "acceptable") {
result_string = "correct";
}
return result_string;`
You can use the contains method defined on Array to check for element membership:
!doc['remark.keyword'].value.contains("acceptable") //does not contain
For this, you might want to ensure first that doc['remark.keyword'].value is indeed an Array.

Multiple query are not inserting data Wordpress

I wrote a function where two insert query have. One is executed and inserting data properly. But next one is not executing. And I cant check the value i want to insert if it is set or not. How to do the stuff? EXPERT's have a look kindly. My function is given below:
add_action( 'save_post', 'cs_product_save' );
function cs_product_save( $post_id ){
global $wpdb;
$cs_product_array = $_POST['cs_product'];
$cs_product_count = count($cs_product_array);
$event_start_date = $_POST['event_start_date'];
$event_end_date = $_POST['event_end_date'];
$event_start_time = $_POST['event_start_time'];
$event_end_time = $_POST['event_end_time'];
$event_all_day = $_POST['event_all_day'];
$event_phone = $_POST['event_phone'];
$event_location = $_POST['event_location'];
$event_map = $_POST['event_map'];
$table_cause_product = "wp_cause_woocommerce_product";
$table_event_info = "wp_cause_info";
for( $i=0; $i < $cs_product_count; $i++ ){
$wpdb->insert($table_cause_product,array(
'cause_ID'=>$post_id,
'product_ID'=>$cs_product_array[$i],
'status'=>'1'
),array('%d','%d','%d'));
}
$wpdb->insert($table_event_info,array(
'cause_ID'=>$post_id,
'event_start_date'=>$event_start_date,
'event_end_date'=>$event_end_date,
'event_start_time'=>$event_start_time,
'event_end_time'=>$event_end_time,
'event_all_day'=>$event_all_day,
'event_phone'=>$event_phone,
'event_location'=>$event_location,
'event_map'=>$event_map
),array('%d','%s','%s','%s','%s','%d','%s','%s','%d'));
}
I don't see any problem here with your code. But be sure to double check your code.
The issues my be with the name of your database table names. Are you sure that $table_cause_product and $table_event_info holds the actual name of the tables? I would recommend to use $wpdb->prefix instead of harcoding table names.
In my case I would check the function in several parts.
Check the $_POST actually holds the data I want.
Use $result = $wpdb->insert( $table, $data, $format ); in all cases for debug purpose as the $result would hold the result of the operation. If its is false then I would be sure that there is definitely something wrong with the operation.
Finally I would use a wp_die() (though its not a standard way to do, but it suffices my purpose) so that I can see the dumped variable data.
One major issue you might face with your code that if the post is edited after saving then it might insert another row for same post data. Again if the post is being autosaved, you need some safeguard. I would recommend a where clause here to check the row already exists or not. If exists then you can simply update the row, or else insert the data.
Hope this might help you.

Filter a product collection by two categories in Magento

I'm trying to find products that are in two categories.
I've found an example to get products that are in category1 OR category2.
http://www.alphadigital.cl/blog/lang/en-us/magento-filter-by-multiple-categories.html
I need products that are in category1 AND category2.
The example in the blog is:
class ModuleName_Catalog_Model_Resource_Eav_Mysql4_Product_Collection
extends Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection{
public function addCategoriesFilter($categories){
$alias = 'cat_index';
$categoryCondition = $this->getConnection()->quoteInto(
$alias.'.product_id=e.entity_id AND '.$alias.'.store_id=? AND ',
$this->getStoreId()
);
$categoryCondition.= $alias.'.category_id IN ('.$categories.')';
$this->getSelect()->joinInner(
array($alias => $this->getTable('catalog/category_product_index')),
$categoryCondition,
array('position'=>'position')
);
$this->_categoryIndexJoined = true;
$this->_joinFields['position'] = array('table'=>$alias, 'field'=>'position' );
return $this;
}
}
When I'm using this filter alone it perform OR query on several categories.
When I combine this filter with prepareProductCollection of Mage_Catalog_Model_Layer
it somehow remove the filter effect.
How can I change the filter to AND and combine it with prepareProductCollection?
Thanks
Thanks
This code will allow you to filter by multiple categories but avoid completely killing performance if you had to perform multiple collection loads:
$iNumberFeaturedItems = 4;
$oCurrentCategory = Mage::registry('current_category');
$oFeaturedCategory = Mage::getModel('catalog/category')->getCollection()
->addAttributeToFilter('name','Featured')
->getFirstItem();
$aFeaturedCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect(array('name', 'price', 'small_image', 'url_key'), 'inner')
->addStoreFilter()
->addCategoryFilter($oFeaturedCategory)
->addCategoryIds();
The first step is to get a collection of products for one category (in this case, a Featured category). Next step is to get the IDs of the products, notice that this does NOT perform a load (ref Mage_Core_Model_Mysql4_Collection_Abstract::getAllIds())
$aFeaturedProdIds = $aFeaturedCollection->getAllIds();
shuffle($aFeaturedProdIds); //randomize the order of the featured products
Then get the IDs for a second category:
$aCurrentCatProdIds = $oCurrentCategory->getProductCollection()->getAllIds();
And intersect the arrays to find product IDs that exist in both categories:
$aMergedProdIds = array_intersect($aFeaturedProdIds,$aCurrentCatProdIds);
For this particular use case, we loop until we have sufficient intersecting products, traversing up the category tree until we find a large enough match (but stopping at root category!):
while(count($aMergedProdIds) < $iNumberFeaturedItems && $oCurrentCategory->getId() != Mage::app()->getStore()->getRootCategoryId()):
$oCurrentCategory = $oCurrentCategory->getParentCategory();
$aParentCatProdIds = $oCurrentCategory->getProductCollection()->getAllIds();
$aMergedProdIds = array_intersect($aFeaturedProdIds,$aParentCatProdIds);
endwhile;
Finally, filter our initial collection by the IDs of the intersecting products, and return.
$aFeaturedItems = $aFeaturedCollection->addIdFilter(array_slice($aMergedProdIds,0,$iNumberFeaturedItems))->getItems();
return $aFeaturedItems;
I am also working on this to no avail, it was available in magento 1.3 using the attribute filter with finset on the category_ids column, however this was moved into the index table from the entity table and now no longer works.
There is one possible solution, but requries an override function which I found here
But this solution is far from ideal.
I think that it will be enough to call addCategoryFilter() twice on your product collection - once for each category. I have not tested it though, so might be wrong.

Resources