I created a custom view field with the hook _views_data and a custom Class who extends FieldPluginBase.  With the render method, I can return a sample string :  class MyCustomClassViewsField extends FieldPluginBase { ...     public function render(ResultRow $values) {       $node = $values-&gt;_entity;       return $node-&gt;id(); // My view field shows the nid of the current node     } ...   Now, I want shows a link with my field. I tried :   class MyCustomClassViewsField extends FieldPluginBase { ...     public function render(ResultRow $values) {       $node = $values-&gt;_entity;       return "&lt;a href='http://www.test.com'&gt;custom link&lt;/a&gt;"     } ...   But my field in my view shows :   &lt;a href='http://www.test.com'&gt;custom link&lt;/a&gt;   and not     How can I show the link as an html element, not a sample text ?   Thank you =)  UP  This code work :   return array('#markup' =&gt; \Drupal::l("test",\Drupal\Core\Url::fromUri("http://www.example.com")));   ut the l() function is deprecated. If I use Link::fromTextAndUrl instead :   return array('#markup' =&gt; \Drupal\Core\Link::fromTextAndUrl("test",\Drupal\Core\Url::fromUri("http://www.example.com")));   I get the error :      [Sun Sep 18 22:17:59.444188 2016] [:error] [pid 2143] [client   192.168.1.48:53322] Recoverable fatal error: Object of class Drupal\Core\Link could not be converted to string in   /var/www/xxxxx/core/lib/Drupal/Component/Utility/Xss.php   on line 67, referer:         [Sun Sep 18 22:17:59.446098 2016] [:error] [pid 2143] [client   192.168.1.48:53322] PHP Fatal error:  Uncaught Error: Call to a member function get() on null in   /var/www/xxxxx/core/lib/Drupal/Core/Session/SessionHandler.php:76\nStack   trace:\n#0   /var/www/xxxxx/vendor/symfony/http-foundation/Session/Storage/Handler/WriteCheckSessionHandler.php(89):   Drupal\Core\Session\SessionHandler->write('BTaHaVF0t-bMk2Z...',   '_sf2_attributes...')\n#1   /var/www/xxxxx/core/lib/Drupal/Core/Session/WriteSafeSessionHandler.php(75):   Symfony\Component\HttpFoundation\Session\Storage\Handler\WriteCheckSessionHandler->write('BTaHaVF0t-bMk2Z...',   '_sf2_attributes...')\n#2   /var/www/xxxxx/vendor/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php(77):   Drupal\Core\Session\WriteSafeSessionHandler->write('BTaHaVF0t-bMk2Z...',   '_sf2_attributes...')\n#3 [internal function]:   Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy->write('BTaHaVF0t-bMk2Z...',   '_sf2_attributes...')\n#4 [internal function]:   session_write_close()\n#5 {main}\n  thrown in   /var/www/xxxxx/core/lib/Drupal/Core/Session/SessionHandler.php   on line 76, referer:      How can I replace the l deprecated function ?
123109
Say I am extending The blockBase class to create a custom block, and I am implementing the blockBuild method to create some markup for my block. Something like this:   class YourModuleBlock extends BlockBase {     /**      * Implements \Drupal\block\BlockBase::blockBuild().      */      public function build() {       return array(         '#markup' =&gt; 'This is a block!',       );      }    }   If I wanted to provide a link in this markup, in D7 I would have used the l function, but this is no longer available (). So, I need to make available the new D8 method for generating links. I could just use an &lt;a&gt; tag, but this was never best practice in D7.  So, what is the right method to use for creating links and how do I make it available to my function?
86495
This is one of those times when I tried to add something and realized that I've got it applied to all displays. This time it was a vocabulary filter, so I clicked cancel and it didn't register so I clicked back to site.  After that I tried to edit and it returned     The website encountered an unexpected error. Please try again later.   The log shows this:     Exception: No entity type for field vid on view VIEW in   Drupal\views\Plugin\views\HandlerBase->getEntityType() (line 712 of   /PATH/core/modules/views/src/Plugin/views/HandlerBase.php).   I checked the active config and couldn't find anything with a vid. Clearing cache and reimporting the view config didn't fix it. So, is there a way?
70055
I've created custom entity. In addition I want to add user reference field to my entity:  if (! field_info_field(MY_FIELD_NAME)) {   // Create the field.    $field = array(     'field_name' =&gt; MY_FIELD_NAME,     'type' =&gt; 'entityreference',     'cardinality' =&gt; FIELD_CARDINALITY_UNLIMITED,     'settings' =&gt; array(         'target_type' =&gt; 'user',         'handler' =&gt; 'base',         'handler_settings' =&gt; array(             'target_bundles' =&gt; array()         ),     ),     'bundles' =&gt; array (         MY_ENTITY_NAME =&gt;             array (                 0 =&gt; MY_ENTITY_BUNDLE_NAME,             ),     ), ); field_create_field($field);      // Create the instance.     $instance = array(         'field_name' =&gt; MY_FIELD_NAME,         'entity_type' =&gt; MY_ENTITY_NAME,         'bundle' =&gt; MY_ENTITY_BUNDLE_NAME,         'label' =&gt; '',         'description' =&gt; '',         'required' =&gt; TRUE,         'widget' =&gt; array(),         'display' =&gt; array(             'default' =&gt; array(                 'label' =&gt; 'hidden',             ),         ),     );      field_create_instance($instance); }   In form submit I want to add users references to this field:     foreach($result as $recipient) {         $wrapper-&gt;{MY_FIELD_NAME}[] = $recipient-&gt;uid;     }   I gets:     Fatal error: Cannot use object of type EntityDrupalWrapper as array   What I am missing?
64273
Currently trying to update a field every time a node is created or updated. However the value is not being populated within the node, do I have access to the node object with this particular hook? What could I be missing?    function vbtoken_node_update($node) {         entity_get_controller('node')-&gt;resetCache(array($node-&gt;nid));         $types = node_type_get_types(); //What are the current Node Content Types?       $yes = ($types['volunteer_project']-&gt;type);        if($node-&gt;type === $yes){           $hash = md5($node-&gt;title . $node-&gt;nid . $node-&gt;nid);         $hashed = substr($hash, 0, 6);         $node = node_load($node-&gt;nid);         $node-&gt;tcode[$node-&gt;language][0]['value'] = $hashed;         node_save($node);          watchdog('vbtoken', 'Added a new Token code to %nid', array('%nid' =&gt; $node-&gt;nid));          }         else          {           dpm('not working dude');         }      }
105914
I have a couple of blocks that have been created using the ... extends BlockBase syntax in my module. They work perfectly fine, and I can add them on the blocks layout page, can add them into DS as a field, etc. They definitely exist fine.  However, when I try and render them using Block::load(), they won't show up, unlike other blocks that work fine.  For example, if I have the following docblock:  /**  * Provides a 'Cute Cats' Block.  *  * @Block(  *   id = "cute_cats",  *   admin_label = @Translation("Cute cats yo"),  * )  */  class CuteCats extends BlockBase { ... }   ... and then try and call it like this:  $block = \Drupal\block\Entity\Block::load('cute_cats'); return render(\Drupal::entityTypeManager()   -&gt;getViewBuilder('block')   -&gt;view($block));   Any idea why? Thanks in advance.
48996
I'd like to implement a simple AJAX function locally that allows me to autocomplete node titles of already existing nodes as the user types. To that end, I need the ability to have an API that I can search on node titles. The problem is that when I output raw JSON, it comes surrounded by tags. So, no matter what I do, I keep getting...  &lt;html&gt;     &lt;head&gt;     &lt;/head&gt;     &lt;body&gt;         &lt;pre style="word-wrap: break-word; white-space: pre-wrap;"&gt; {json here}&lt;/pre&gt;     &lt;/body&gt; &lt;/html&gt;   I've tried implementing a custom page template that only outputs content already, that produced the same results. Here is how I am currently doing this, in my module file...  &lt;?php  /**  * Implementation of hook_menu()  */ function content_relation_menu() {     $items = array();     $items['api'] = array(         'title' =&gt; 'Search',         'page callback' =&gt; 'content_relation_get',         'access callback' =&gt; TRUE,         'type' =&gt; MENU_CALLBACK,     );      return $items; }  function content_relation_get($term = '') {     drupal_add_http_header('Content-Type', 'application/javascript; utf-8');     $var = json_encode(         db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" =&gt; $term.'%'))-&gt;fetchAll()     );     echo $var;     exit(0); }   How can I return JUST raw JSON?
96555
i create a custom page to display loop of cpt with custom field.   I need to add a numberic pagination and i try with this code but not work.  Functions.php  function pagination_bar() {     global $wp_query;      $total_pages = $wp_query-&gt;max_num_pages;      if ($total_pages &gt; 1){         $current_page = max(1, get_query_var('paged'));          echo paginate_links(array(             'base' =&gt; get_pagenum_link(1) . '%_%',             'format' =&gt; '/page/%#%',             'current' =&gt; $current_page,             'total' =&gt; $total_pages,         ));     } }   custompage.php  &lt;!--Loop Salmi--&gt; &lt;?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $loop = new WP_Query( array( 'post_type' =&gt; 'salmi',         'posts_per_page' =&gt; 15,         'paged'          =&gt; $paged ) ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt;      &lt;!--Colonne Contenuto --&gt;     &lt;div class="salmicpt"&gt;         &lt;div class="wpb_column vc_column_container td-pb-span8"&gt;             &lt;div class="titlecpt"&gt;&lt;?php the_title(); ?&gt;&lt;/div&gt;         &lt;/div&gt;         &lt;div class="wpb_column vc_column_container td-pb-span4"&gt;             &lt;?php if( get_field('audio_salmi') ): ?&gt;                 &lt;a href="&lt;?php the_field('audio_salmi'); ?&gt;" &gt;&lt;img src="mysite.com/wp-content/uploads/cuffia-cpt-e1481533293805.png" alt="Ascolta" title="Ascolta" /&gt;&lt;/a&gt;             &lt;?php endif; ?&gt;             &lt;?php if( get_field('salmi_pdf') ): ?&gt;                 &lt;a href="&lt;?php the_field('salmi_pdf'); ?&gt;" &gt;&lt;img src="mysite.com/wp-content/uploads/freccia-32.png" alt="Scarica il PDf" title="Scarica il PDF" /&gt;&lt;/a&gt;             &lt;?php endif; ?&gt;         &lt;/div&gt;         &lt;div style='clear:both'&gt;&lt;/div&gt;&lt;hr class="style-one" /&gt;     &lt;/div&gt;     &lt;nav class="pagination"&gt;         &lt;?php pagination_bar(); ?&gt;     &lt;/nav&gt;  &lt;?php endwhile; wp_reset_query(); ?&gt;    Where is wrong?? Thanks
7510
How do I add an autocomplete field in a class that extends FormBase?  I created a custom module, which uses a class that extends FormBase. I want to  programmatically create a form field that autocompletes the username from the user registered in the site.
98618
How do I load an image from a taxonomy custom field into a custom location on the taxonomy page template?  It's easy to accomplish it when the image is in a node. The following code works for images, but it doesn't work for taxonomy pages.      {{ file_url(node.field_reference_background.entity.uri.value) }}   How can I accomplish the same for taxonomy pages?
123090
In Drupal 8, I have a content type, that has an "entity_reference" field and I wish to access the referenced node's fields in twig template. the kint() output for the field is:   In this list I can't find the referenced node's field values. How can I (if at all possible) load the node or node fields/values in twig?  Best,  Alari
86546
I have been trying to integrate Google Shortener API into my salesforce org. I wrote a class to make the call out, but am having difficulty bringing the value back into the record. I have a custom object called "referral_advocate__c" with a field called "Short_URL__c". Anytime the field "unique_ID__c" has a value, I am wanting to send this value with a static URL to google shortener and then save the response value to "referral_advocate__c.short_URL__c" on the record. This is the class to make the call out:  public class URLshort {  final string urls = 'https://www.myurl.com'; referral_advocate__c adv = new referral_advocate__c();  @future(callout = true) public static void URLshortner() {      HttpRequest req = new HttpRequest();     HttpResponse res = new HttpResponse();     Http http = new Http();      req.setEndpoint('https://www.googleapis.com/urlshortener/v1/url?key=myapikey');     req.setMethod('POST');     req.setHeader('Content-Type','application/json');            req.setBody('{"longUrl":+urls + adv.unique_reference_number_c}');       try {         res = http.send(req);         System.debug(res.getBody());     } catch(System.CalloutException e) {         System.debug('Callout error: '+ e);         System.debug(res.toString());     }   }  }   The after insert trigger on "referral_advocate__c" I wrote is not firing correctly. How do I return the results from this class and update the field "short_URL__C" with the returned value from a trigger?
91992
I am following the code snippet provided here  {# Link to frontpage view. #} &lt;a href="{{ path('view.frontpage.page_1') }}"&gt;{{ 'View all content'|t }}&lt;/a&gt;  {# Link to user entity/profile page. #} &lt;a href="{{ path('entity.user.canonical', {'user': user.id}) }}"&gt;{{ 'View user profile'|t }}&lt;/a&gt;  {# Link to node page. #} &lt;a href="{{ path('entity.node.canonical', {'node': node.id}) }}"&gt;{{ 'View node page'|t }}&lt;/a&gt;     As the function says path($name, $parameters, $options), I want to add a link which has query parameters as shown in below  blue?destination=blue-search&amp;cookie[blue_referrer]=3622&amp;cookie[blue_type]=node   I tried implementing it as follows   &lt;a href="{{                 path('blue_general.blue',                {'node': node.id},                 {'query': [                  'destination': path('view.blue_search.page_1'),                  'cookie[blue_referrer]': node.id,                  'cookie[blue_type]':'node'                  ]                  }                )                 }}"&gt;Find a Distributor&lt;/a&gt;   but it gives an error     The website encountered an unexpected error. Please try again   later.Twig_Error_Syntax: An   array element must be followed by a comma. Unexpected token   &quot;punctuation&quot; of value &quot;:&quot;   (&quot;punctuation&quot; expected with value &quot;,&quot;). in Twig_TokenStream-&gt;expect() (line 124 of /templates/node/node--product.html.twig).   Twig_ExpressionParser-&gt;parseArrayExpression()   (Line: 205)
29281
In my page.tpl.php I'm doing this to display one of my view:  print views_embed_view('teaserview', 'default');   That gives me the following html output:  &lt;span thmr="thmr_10"&gt; &lt;div class="view view-teaserview view-id-teaserview view-display-id-default view-dom-id-e051ba535ce9aac6cd9a0d564b3dbb29 contextual-links-region"&gt;     &lt;div class="contextual-links-wrapper"&gt;         &lt;span thmr="thmr_16"&gt;         &lt;ul class="contextual-links"&gt;             &lt;li class="views-ui-edit first last"&gt;&lt;span thmr="thmr_17"&gt;&lt;a href="/kbi/admin/structure/views/view/teaserview/edit/default?destination=node/3"&gt;Edit view&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;         &lt;/ul&gt;         &lt;/span&gt;     &lt;/div&gt;     &lt;div class="view-content"&gt;         &lt;span thmr="thmr_15"&gt;         &lt;div class="views-row views-row-1 views-row-odd views-row-first views-row-last"&gt;             &lt;span thmr="thmr_14"&gt;             &lt;span thmr="thmr_11"&gt;&lt;span thmr="thmr_12"&gt;&lt;span thmr="thmr_13"&gt;&lt;img src="http://127.0.0.1/kbi/sites/default/files/teaser_2.jpg" width="1029" height="308" alt="" /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;         &lt;/div&gt;         &lt;/span&gt;     &lt;/div&gt; &lt;/div&gt; &lt;/span&gt;   But the only thing that I really need is  &lt;img src="http://127.0.0.1/kbi/sites/default/files/teaser_2.jpg" width="1029" height="308" alt="" /&gt;   Is there a possibility to modify the views_embed_view call so that I get only the needed data?   There would be the possibility to modify all the views .tpl.php files but I hope there's an easier way to do this.   I also read about the semantic views module but I didn't understand how to configure my view with it so that i get only the needed markup as output. it didn't seem to have any effect.
96983
I have extended class WP_List_Table to create a custom sortable table of posts along with a quick edit box with custom meta boxes.  The meta boxes populate and save but when I click submit the field values disappear and the defaults ( cb, title, tags, cats, etc) which are not even included in my class get added back to the column saved. This throws off the other columns on the page.  The saved custom field values return when the page is refreshed.  It seams like on submit the $post_object is missing.  I'm using a hacked get_inline_data function that includes the meta_values in my quick edit form instead of calling get_inline_data in my class.  My save function for the meta boxes:  add_action( 'save_post', 'save_inline_edit_meta' ); function save_inline_edit_meta( $post_id  ) {     global $pagenow;      if ( $pagenow == 'admin.php' ) {      if ( isset( $_POST[ 'is_quickedit' ] )  &amp;&amp; isset( $_POST[ 'standinghead' ] ) )         update_post_meta( $post_id, '_wnd_standing_head', $_POST[ 'standinghead' ] );      if ( isset( $_POST[ 'is_quickedit' ] )  &amp;&amp; isset( $_POST[ 'headline' ] ) )         update_post_meta( $post_id, '_wnd_alt_title', $_POST[ 'headline' ] );      if ( isset( $_POST[ 'is_quickedit' ] )  &amp;&amp; isset( $_POST[ 'deck' ] ) )         update_post_meta( $post_id, '_wnd_deck', $_POST[ 'deck' ] );     }   return $post_id;  }   My Javascript save function:  save : function(id) {         var params, fields, page = $('.post_status_page').val() || '';          if ( typeof(id) == 'object' )             id = this.getId(id);         $('table.widefat .inline-edit-save .waiting').show();         params = {             action: 'inline-save',             post_ID: id,             post_type: 'post',             edit_date: 'true',             post_status: page         };         fields = $('#edit-'+id+' :input').serialize();         params = fields + '&amp;' + $.param(params);          $.post('admin-ajax.php', params,             function(r) {                 $('table.widefat .inline-edit-save .waiting').hide();                  if (r) {                     if ( -1 != r.indexOf('&lt;tr') ) {                         $(inlineEditPost.what+id).remove();                         $('#edit-'+id).before(r).remove();                         $(inlineEditPost.what+id).hide().fadeIn();                     } else {                         r = r.replace( /&lt;.[^&lt;&gt;]*?&gt;/g, '' );                         $('#edit-'+id+' .inline-edit-save .error').html(r).show();                     }                 } else {                     $('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();                 }             }         , 'html');         return false;     },
73668
In Drupal 8, I have a view that gathers all the nodes built in my Gallery Hours content type.  The content type has a field called View Order that I use for another view that displays the list of gallery hours in that order.  What I am trying to do is to build another view that checks for the gallery hours for today.  For instance, today is Tuesday, so I would like the view to display the gallery hours for Tuesday.  My thought was to create a custom filter option that compares the numeric value of a field, such as my View Order field which is set to 1=Sunday, 2=Monday, etc., with DATE_FORMAT(NOW(),"%N"). This is my first foray into custom Drupal module development and am spinning my wheels.  Any and all suggestions welcome.  The one thing I think I have correct are my yaml files.  todaysdate.info.yml   name: Todays Date Filter module description: 'Creates a filter to search by todays day of the week.' type: module core: 8.x package: SMA Modules     todaysdate.routing.yml   todaysdate:   defaults:     _controller: Drupal\todaysdate\Plugin\Filter\todays_date_handler_filter_numeric::operators   requirements:     _permission: 'access content'     Where I am really confused is where to go from there.  I am trying to piece together a class that extends the NumericFilter and add a new operator that then add to the WHERE expression with the dateformat I'm looking for.  Anyhoo, this is my attempt at creating the filter.  I am not getting any errors, but I am also not getting the new operator on my numeric fields in my view.  todays_date_handler_filter_numeric.php   &lt;?php  /**  * @file  * Provides views filter option for the Todays Date module.  */  namespace Drupal\todaysdate\Plugin\Filter;  use Drupal\views\Plugin\views\display\DisplayPluginBase; use Drupal\views\Plugin\views\filter\NumericFilter; use Drupal\views\Plugin\views\filter\InOperator;  class todays_date_handler_filter_numeric extends NumericFilter {   function operators(){     $operators = parent::operators();     $operators += array(       'todays date' =&gt; array(         'title' =&gt; $this-&gt;t('Is this day of the week'),         'short' =&gt; $this-&gt;t('todays date'),         'method' =&gt; 'op_day_of_week',         'values' =&gt; 0,       )     );     return $operators;      function op_day_of_week($field) {       $this-&gt;query-&gt;addWhereExpression($this-&gt;options['group'], 'DATE_FORMAT(NOW(),"%N")');     }   } }     Thank you all in advance for any assistance you can provide.  I can't tell you how many times StackOverflow has helped me in the past.
107826
I have a custom block containing a text field and an image field. I would like to render the block so that the image's URL can be defined as a data attribute of the block's wrapper div so that it can be used by a javascript function to create a parallax background effect behind the text field.  If I make a template file block.parallax.html.twig, I am able to render the image HTML.  {{ content.field_parallax_image.0 }}   However If I try to get the actual image URL, nothing is returned  {{ content.field_parallax_image.0['#url'] }}   If I dump the #item keys  {{ dump(content.field_parallax_image.0['#item']|keys) }}   I am able to get target_id, alt, title, width and height values, but I can't find the URL defined anywhere.  I have also tried to see if I could find anything useful in the block preprocess function but the field_parallax_image #url field in the variables is also empty  function mytheme_preprocess_block(&amp;$variables) {     if( isset($variables['content']['body']['#bundle']) &amp;&amp; $variables['content']['body']['#bundle'] == 'parallax'){         $variables['img_url'] = $variables['elements']['content']['field_parallax_image'][0]['#url'];     } }   Is there a way I can get this URL?
122208
in short: Something in my zen-based custom theme is keeping a couple of cck fields from being display on my page. Basically my question is where to get access to the variables that are supposed to contain the html for the cck fields (which are missing when I was looking them in firebug). Below I explain why I think it's looking up the variables that might bring me closer to a solution  So I made this custom node type (events) with cck fields added. Also made some content using those fields. Added some css and it all displayed fine. Later the taxonomy terms below the title and some metadata bugged me so I followed along with a 'theming cookbook' pdf book that taught me how to make a node-events.tpl.php and simply deleted php variables like $terms. This worked great.     Obviously this also means that all this time, the view permissions of those fields have been checked and also that the display options under 'display fields' have been set to standard all the time. I also ruled out that the issue could be anything else than theme related as my cck fields do show up in a stock Drupal theme. The theme for my site is a zen-based custom theme.   So then even later, after I made a view for this node type and started adding css to that view I noticed at some point that my image field and two other fields are missing. It's hard to tell if they disappeared because of things that I did when creating the view and adding css (which would surprise me)