jsonapi Cross-Origin Read Blocking (CORB) blocked cross-origin response in vue I got the data with postman in json:api at drupal.

 But I has error of CORB in  Vue-resource.get() with code blew：

 data(){
    return{
        cyclePic:[],
        rootUrl:this.$http.options.root,
        header:{headers:{Accept:'application/vnd.api+json',
            'Content-type':'application/vnd.api+json',
            Authorization:"Basic dG1wQWRtaW46VG1wQDEyMyM0NTY="}
            }
    }
},
created(){
    this.getCycleList()
},
methods:{
    getCycleList(){

        this.$http.get('jsonapi/node/banner?include=field_image',this.header).then(result=>{
            console.log(result)

            if(result.ok && result.status===200){
                this.cyclePic=result.body.included
                console.log(this.cyclePic)
            }else{
                Toast('Fail')
            }

        })
    }

what i miss some thing?

You need to set up your Cors settings
Look at your services.yml file then read ...

How do I set up CORS?


How do I display a block on an edit form for particular content types? It's fairly simple to display a block on the node add form for a particular content type. Simply restrict visibility to a URL path like node/add/article and you're good to go.

I would like to know how to display a block on the edit form for a particular content type. For instance, when editing an article, the URL path is node/NID/edit.

Is there an easy way to display a block for edits of a given content type?

You need to add php code in the block Visibility settings in admin section of block. You can follow below code.

$node = menu_get_object();

   if (isset($node) && $node->type == 'article' && arg(2) == 'edit') {

     return TRUE;
   }

   return FALSE

Another example:

$nid = arg(1);

   $node = node_load($nid);

   if (isset($node) && $node->type == 'article' && arg(2) == 'edit') {

     return TRUE;
   }

   return FALSE


is it ok to manually remove menu_links entries from db? To my surprise, I removed one menu item from the main menu, and it correctly dissapeared from the admin ui, but there still is an entry in the table called menu_links. There is nothing unusual about the entry. How does drupal know it should not be used ? Can I manually remove it ?

The problem is, I use custom code that traverses the menu_links table to generate an alternative menu. This custom code just sees the menu item and keeps on displaying it in the alternative menu. So, is that approach wrong ?

The menu_links table contains a lot of automatically generated rows. These come from the hook_menu() implementation of modules. Deleting these rows will likely result in them returning on the next time you clear the cache, because menus will be rebuilt than and the systems scans through all hook_menu() implementations adding new links.

If you look closely at the menu_links table, you'll notice there is a boolean field hidden. A value of 1 tells Drupal not to show this item in menu's.

So you can either filter out all hidden items (you only need hidden = 0 since the value -1 represents a menu callback), or you can have a look at the Drupal menu functions. There are a lot of functions with menu and tree, but if I am not mistaken you are looking for menu_build_tree.


How to create a redirect form? I have a very important tag list (over 100k) (drupal 8).

I'm using the default view of taxonomy.

I need a form in my navbar that allows me to redirect to the different lists related to my tags generated with taxonomy view.

For example:

I type in the form "term 1",
then appears the list of all the contents tagged with the "term 1", with for url mysite/term-1 (important).

I tried to modify the taxonomy view with an exposed form but it does not work, because it is necessary that the form allows to search in all the site and not to filter the list displayed.

I tried to create a content view with an exposed form to sort by terms of taxonomy, it works but I have url problems not optimal for SEO (ex: mysite/myview?tid=taxonomy+term+(3)).

I thought of an element of type select with autocomplete (as chosen) but considering the number of tags I do not think it is recommended. Creating a menu seems to me also not recommended.

In short, I do not find the solution!

Does somebody have an idea ?

To get the form with a suggestions list like that you need to create an exposed filter in your content Views and use Exposed form in block option. Place the block in a region of your theme.

To get the autocomplete suggestions list for taxonomy terms use the Has taxonomy terms filter and set it to Autocomplete.

The Global filter doesn't seem to work with taxonomy fields, I'm not sure if there are combinations you can try to make it work and have all the vocabularies terms searchable in one field.

The default Taxonomy term Views contextual filter needs to be removed since it won't work with only exposed filter output unless you use Views Filter Harmonizer.

Query Parameters To URL can help with the SEO side of things.

To get the Term name into your content Views instead of the TID you have to add a Relationship to the related Taxonomy term field. Then you'll be able to add Fields, Filters and Contextual filters based on the "Name", but the widgets might not offer autocomplete or other options you have under "Has taxonomy term".

Alternatively you can create a "Taxonomy term" TYPE of views where you can get the Name filter for all vocabularies, but no autocomplete.

(Add Relationship to content so you can show nodes in the results.)

Search Autocomplete might help partially, maybe you can get it to direct to a specific views page with the result as argument.

Using a more powerful Search API or other search features related to Views might allow you to achieve everything you're asking about.


Is there a module that saves Twitter posts in a custom table? I need to save Twitter posts in Drupal 7, but I don't want to create a node for each tweet.

Is there a module that can save them in a custom table?

Thanks.

Try the feeds module and data module

http://drupal.org/project/feeds
http://drupal.org/project/data

and import the rss of your twitter feed or search into the feed than save it as a simple database record with the data module.


Define module as feature Creating a module with Drupal Composer asks me:

  Define module as feature (yes/no)

What does it mean?

That option will add some code to the generated module to make it a Feature module - a module that provides some exportable configuration.

More info: https://www.drupal.org/docs/8/modules/features/creating-and-configuring-bundles
Source: https://github.com/hechoendrupal/drupal-console/blob/master/src/Generator/ModuleGenerator.php#L94


How to resolve the error "Base table or view not found"? When I connect my custom module with database external

$database = array(
  'host' => 'localhost',
  'database' => 'DATABASE1',
  'username' => 'root',
  'password' => 'root',
  'driver' => 'mysql',
);
Database::addConnectionInfo('mykey', 'default', $database);
   db_set_active('mykey');

it gives error on running the module

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'DATABASE1.filter_format' doesn't exist: SELECT
  ff.* FROM {filter_format} ff WHERE (status =
  :db_condition_placeholder_0) ORDER BY weight ASC; Array (
  [:db_condition_placeholder_0] => 1 ) in filter_formats() (line 434
  of /var/www/html/drupalprac/modules/filter/filter.module).

  Uncaught exception thrown in shutdown function.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'DATABASE1.semaphore' doesn't exist: DELETE FROM
  {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array (
  [:db_condition_placeholder_0] => 1595456215ac3545f2ff1c3.60338979 )
  in lock_release_all() (line 269 of
  /var/www/html/drupalprac/includes/lock.inc). Uncaught exception thrown
  in session handler.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'DATABASE1.sessions' doesn't exist: SELECT 1 AS
  expression FROM {sessions} sessions WHERE ( (sid =
  :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1)
  ); Array ( [:db_condition_placeholder_0] =>
  gSAxKMpfVXzf2EVP4EWBtuF2klcg0RZie30ztTTUjKc
  [:db_condition_placeholder_1] => ) in _drupal_session_write() (line
  209 of /var/www/html/drupalprac/includes/session.inc).

You need to switch the database back before it carries out any operation that requires the Drupal database.

// Switch to your custom database.
db_set_active('mykey');

// Work with that database (select/insert/update).
...

// Switch back, before you use the Drupal API again
db_set_active();


Which function should I use to update a node through the comment form? I use this function to synchronize a comment field with the value from a field that exists in the node the comment belongs to.

function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
  $node = $comment->getCommentedEntity();
  if ($node && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->hasField('field_example')) {
      $comment->subject->value = $node->field_example->value;
    }
  }
}

How could I achieve the opposite? When a comment is submitted with the field field_rating, the field_average_rating field of the node should be updated.

How could I achieve that?

You could implement the same hook hook_comment_create() but just inverse the assignment you do on the comment as in your code, for example:

function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
  $node = $comment->getCommentedEntity();
  if ($node && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->hasField('node_field') && $comment->hasField('comment_field') && !empty($comment->comment_field->value)) {
      $node->node_field->value = $comment->comment_field->value;
    }
  }
}


Add signature in node I was trying to add signature in every node in my drupal 7. I found this the code was for drupal 6. What would be the code for Drupal 7? please help me because I have no idea about drupal api.
Thanks

If the "signature" doesn't contain any special programmatical behavior and its basically textual (whether styled with CSS and/or images or not)

Than I have the ultimate simple solution for you:

Create a block with the desired content, and place it under your "Content" block on your main content region by going to Structure > Block layout.

The signature-block will now appear under every page/node (you could filter where it would appear by means of content type or NID -> Node ID number).


Why isn't the image added in the block settings shown in the front end? When I try to add a background image in Bootstrap block settings (the settings added by the BB Animation Module) Drupal uploads it, but the image doesn't appear on the front end.

Any help about this?

I applied a patch for this module. This got disturbed due to the media module update.

At line no 300 in bb_animation.module.I changed the code

from

$file = file_load($background_image['fid']);

To

$background_image_data_type = gettype($background_image);
switch ($background_image_data_type) {
        case 'array':
            $file = file_load($background_image['fid']);
            break;
        case 'string':
            $file = file_load($background_image);
            break;
    }


Hide and show logo based on user role Drupal 7

Is it possible to write an if statement in the page.tpl.php file that first gets the user role and then compares it to a string and it either shows the logo or doesn't. Something like...

//some how get user role

global $user;
$user_fields = user_load($user->uid);

$current_role = $user_fields->role[];

if ($current_role == "public_user"){
>?
<?php
 print $front_page;
?>" title="

<?php
 print t('Home');
?>
" rel="nofollow">

?>
}else{
//don't show.
}

I'd suggest checking against a permission, rather than an entire role.

In your custom module, add:

function mymodule_permission() {
    return array(
        'view site logo' => array(
            'title' => t('View Site Logo'),
            'description' => t('Allows a user to view the site logo'),
        ),
    );
}

And in your theme's template.php page preprocessor, add:

if(!user_access("view site logo")) {
    $variables['logo'] = "";
}

This way, $logo will not be processed in page.tpl.php for a user without the permission.


Drupal7 Get results from a form in a table I want to show my result from the form in the table on the same page.

//my form
function find_tryk_filter_test_form_page($form, &$form_state)
{
$form['submit']         = array(
    '#type' => 'submit',
    '#value' => t('Find trykluft element'),
    '#ajax' => array(
        'callback' => 'find_tryk_filter_test_ajax_result_callback',
        'wrapper' => 'result-wrapper',
        'method' => 'click'
    )
);

return $form;
}

My page callback function

function find_tryk_filter_test_page()
{
  $page = drupal_render(drupal_get_form('find_tryk_filter_test_form_page'));
  $page .= filter_elementer_rows($form_state['values']['dropdown_third']);
  print_r($page);
  return $page;
}

The function that retrives my data and create the table

function filter_elementer_rows($value_dropdown_third)
{
  $header = array(
    'Navn',
    'Shoplink',
    'Brochure'
   );
  $query  = db_query(//Some sql statement...));
  $rows   = array();
  foreach ($query as $row) {
    $rows[] = array(
        $row->title,
        $row->field_shoplink_value,
        $row->uri
    );
}
  return theme('table', array(
    'header' => $header,
    'rows' => $rows
  ));
}

My submit function

function find_tryk_filter_test_page_submit($form, &$form_state)
{
   return find_tryk_filter_test_page();
}

My problem is that when I run this, I get absolutely nothing in the table. And the SQL does work. Do I miss anything?

The return value from a form submit function isn't used. What you need to to is rebuild the form, and alter the original form function to display the table if it's available. For example:

function find_tryk_filter_test_form_page($form, &$form_state) {
  if (isset($form_state['render_table'])) {
    $form['table'] = array('#markup' => find_tryk_filter_test_page());
  }

  $form['submit'] = array(
   '#type' => 'submit',
    '#value' => t('Find trykluft element'),
    '#ajax' => array(
        'callback' => 'find_tryk_filter_test_ajax_result_callback',
        'wrapper' => 'result-wrapper',
        'method' => 'click'
    )
  );

  return $form;
}

function find_tryk_filter_test_page_submit($form, &$form_state) {
   $form_state['render_table'] = TRUE;
   $form_state['rebuild'] = TRUE;
}

Or you might redirect to a page that has your table on it, if that makes sense:

function find_tryk_filter_test_page_submit($form, &$form_state) {
   $form_state['redirect'] = 'foo/bar/path';
}


getting error when clear cache in drupal Following Error occure when i clear cache from admin in drupal:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry 'seven-views-retailers_view-block' for key 'tmd':
  INSERT INTO {block} (module, delta, theme, status, weight, region,
  pages, cache) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6,
  :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => views
  [:db_insert_placeholder_1] => retailers_view-block
  [:db_insert_placeholder_2] => seven [:db_insert_placeholder_3] => 0
  [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => -1
  [:db_insert_placeholder_6] => [:db_insert_placeholder_7] => -1 ) in
  drupal_write_record() (line 7106 of
  /home/nxsol/webdata/latestspecialsonline.co.za/includes/common.inc).

Consider using db_merge if you want to write when the record doesn't exist and update if the record exists. In fact at the business logic level you should check if a record exists or not before making an insert or update. That way you will have more control.

And regarding the problem you are facing only when you clear cache, it can be that somewhere in your code when you have an entry in cache you are not making an insert. But when there is no entry in the cache, you are making an insert. So every time you clear the cache an insert is being attempted with the same key which might be causing the problem.


what are the different ways to use the variable in many functions within a module? I want to access a variable changed in one function in another. I tried this with Session and global variables. I need the variable to be persisted across multiple page requests. are there any other ways to do this?

variable_set

  sets a persistent variable.

  Case-sensitivity of the variable_* functions depends on the database
  collation used. To avoid problems, always use lower case for
  persistent variable names.

variable_get

  Returns a persistent variable.

  Case-sensitivity of the variable_* functions depends on the database
  collation used. To avoid problems, always use lower case for
  persistent variable names.

variable_del

  Unsets a persistent variable.

  Case-sensitivity of the variable_* functions depends on the database
  collation used. To avoid problems, always use lower case for
  persistent variable names.


Get a field instance's settings What's the equivalent of field_info_instance() for Drupal 8?

The default field settings are stored as configuration in a file like field.field.ENTITYTYPE.BUNDLE.FIELDNAME.yml, but how do I get their current value?

Using the entity_field.manager service, you are able to get an array of BaseFieldDefinition classes. This service is injectable as well, but for copy-paste working code, you can do the following:

$bundle_fields = \Drupal::getContainer()->get('entity_field.manager')->getFieldDefinitions($entity_type, $bundle);
$field_definition = $bundle_fields[$field_name];
$catalog_id = $field_definition->getSetting($setting_name);


theme superfish menu item link add query string I need to add the destination to user/logout links in the THEME_superfish_menu_item_link preprocess function, but I am having no luck.

In template.php I have:

function THEME_superfish_menu_item_link(array $variables) {
  if ($variables['menu_item']['link']['link_path'] == "user/logout") {
    $dest = drupal_get_destination();
    $link_path = $variables['menu_item']['link']['link_path'] . '?destination=' . $dest['destination'];
    $menu_link = l($variables['menu_item']['link']['title'], $link_path, $variables['link_options']);

    return $menu_link;
  }
}

My links end up encoded: /user/logout%3Fdestination%3Dhome

I assume query strings can be added as parameters to the $variables['menu_item'] but am unsure how.

I think your problem is in how you add the query string. Check this article: Webemania | How and why to use l() function to create links in Drupal and specifically example 6.

<?php
// adding query string on example:5
print l(  t('PHP ini configuration'),  'node/33',  array('attributes' =>array('class'=>'php-ini-conf', 'id'=>'phpini-conf'), 'query'=>array('id'=>'5','status'=>'ok') ));
?>


Hosting advanced cron for Aegir 3 There was one very useful contributed module named Hosting Advanced Cron. It allowed me to set cron interval per site, instead of set just global for all (and you can even disable cron on specific sites). hosting advanced cron

For Aegir 3, there is no such release and development seemed to be stopped. There is a fork on Github by omega8cc, but it is not functional (doesn't work, has error and notice, has debug statements left on), so does anyone have a solution or a replacement for such a useful feature for Aegir 3?

After discussion with omega8cc, and a bit of testing, the answer is that advanced_cron is not any more compatible with Aegir 3. It is also merged into BOA (by omega8cc) in their core, and it is not back compatible with stand alone Aegir.

There are two options:

port it to work with standalone Aegir 3
use crontab and wget / curl to trigger cron on site


How can I access location information via rules, to include the City of a node in an email? I have a rule, which works like this:
After saving new content, Fetch users who have flagged a Taxonomy term, Loop, send email.
The emails get sent perfectly, to users who have flagged the specific term.

Now I would like to include the location, from the new content item which is saved, in the email.

If I look for the relevant Replacement Patterns [node:location] is available, but does not print anything when included in the email. I'm guessing this is because [node:location] is an array and I need to do something else to explode the array to get "City" out and print it in the email...

Does anyone know how I would do that? Or a better way to access the specifics (i.e. City) from a node location?

NB: The Location information for my content type is NOT added as "fields" but is added to the content type under "Locative information" (next to Comment Settings and Menu Settings in D7) I am only collecting City and Postcode (and forcing Country to the default)

The Location module defines tokens for each piece of info (see below from location.tokens.inc)

So based on this, [node:location:city] should work for a single value, or [node:location:city:0] for the first value if there were multiple values.

  $location['name'] = array(
    'name' => t("Location Name"),
    'description' => t('Location Name (If there are multiple locations, N is the iteration, starting with 0).'),
    'dynamic' => TRUE,
  );
  $location['street'] = array(
    'name' => t("Street"),
    'description' => t("Street (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['additional'] = array(
    'name' => t("Additional"),
    'description' => t("Additional (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['city'] = array(
    'name' => t("City"),
    'description' => t("City (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['province'] = array(
    'name' => t("State/Province"),
    'description' => t("State/Province (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['province_name'] = array(
    'name' => t("State/Province Name"),
    'description' => t("State/Province Name (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['postal_code'] = array(
    'name' => t("Postal Code"),
    'description' => t("Postal Code (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['latitude'] = array(
    'name' => t("Latitude"),
    'description' => t("Latitude (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['longitude'] = array(
    'name' => t("Longitude"),
    'description' => t("Longitude (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['country'] = array(
    'name' => t("Country"),
    'description' => t("Country (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['country_name'] = array(
    'name' => t("Country Name"),
    'description' => t("Country Name (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );


How to add Title attribute to Menu links? Is it possible to add Title attribute to Menu items? If so, how?

Just enter text in the description field and it will be rendered as the link title.


drush extension installation directory location Where is the recommended location to install drush extensions?

I've downloaded drush_sup and have drush 5.4 installed.

drush_sup/README.txt says to look in the drush README.txt file for the recommended location:

  See the Drush README.txt for locations where Drush extensions may be
  placed.

drush/README.txt does not discuss extensions.

This (the incorrect contents in the drush_sup README file) is a drush_sup bug report, and should go in the drush_sup issue queue.  I am the drush_sup maintainer, though, and can make this correction.

If you use Drush to download drush sup (i.e. drush dl drush_sup), then it will automatically be placed in the .drush folder in your home directory.  Drush automatically finds extensions stored in this location.


How do I print main_menu? I try to render a main menu but it doesn't render. My old Drupal 6 template try to upgrade Drupal 7 template.

I've render in page.tpl.php.

<?php if (isset($main_menu)) : ?>
    <?php print phptemplate_primary($main_menu); ?>
  <?php endif; ?>

This is the code for phptemplate_primary().

function phptemplate_primary() {
  $output = '
';
  $element = menu_tree(variable_get('menu_primary_links_source', 'primary-links'));
  $output .= drupal_render($element);
  $output .= '
';
  return $output;
}

How do I resolve this problem?

You can do it both ways:

You can add menu block to your template - just like any other block (this method is the easiest).
If you need more customization, you can do it in template:

page.tpl.php

<?php if ($primary_nav): print $primary_nav; endif; ?>

template.php

if (isset($variables['main_menu'])) {
  $variables['primary_nav'] = theme('links__system_main_menu', array(
    'links' => $variables['main_menu'],
    'attributes' => array(
      'class' => array('links', 'inline', 'main-menu'),
    ),
    'heading' => array(
      'text' => t('Main menu'),
      'level' => 'h2',
      'class' => array('element-invisible'),
    )
  ));
}
else {
  $variables['primary_nav'] = FALSE;
}


Function breaks chart.js I am trying to insert my chart.js into a Drupal page.
Here is the fully functional fiddle:
http://jsfiddle.net/vy0yhd6m/80/

When I enter that into a basic page content item in Drupal, the chart will not display.
However, if I remove scaleLabel(), it works and displays perfectly on the Drupal page. For some reason, adding that function in the Full HTML content item makes the chart disappear, even though it works perfectly in the above JS Fiddle.

scaleLabel: function(label){return  ' $' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");}

Does anyone have any idea on why this is happening?

So I realized I was using an outdated version of Chart.js (from an old production site).
I just updated to the latest version, and now all is well with the world.

Thanks.


Getting values on twig node template I have installed ECK module in my website. Using it I have created a "report eck" entity in which I have different bundles like section, notes, etc., each containing different fields.
I have my content type "Report" in which I have referred "report eck" entity using entity reference field.
Now, in my nice template, I need to get various values including the bundle type, in which I am facing lots of trouble. My bundle type is coming up as following when I am doing kint() on my reference field, but I am not able to get this bundle type and many other values, please guide.

Also, it seems to be a protected values, so I navigated to "Available Methods" tabs and found method 'getEntityKey()' which seems to be useful, but how can I use it in twig template??

These are protected. You need to use any available getters to access them. Example, for nodes, the method is getType(). $node->getType(). Most generic entities should have a bundle() method that returns type.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3Abundle/8.4.x

Examples:

$bundle = $myEntity->bundle();

$variables['bundle'] = $bundle;

Twig: {{ bundle }}


How do I render the view of an entity reference? I have a custom view which has a field that references another view. How do render the referenced view. I can't see the Render View option.

Below is an attached image for clarity. The top screenshot shows my current setup, while the bottom image shows my expected result.

Also both screenshots are taken from different sites and running the same version of Drupal 8.5.3

Views are config entities, and as such not rendered like content entities. When you reference a config entity, all you get out of the box are two formatters that can render data which all config entities will definitely have: An ID, and a label.

You need a formatter that knows how to render a View display rather than the View entity itself. Core doesn't come with one unfortunately.

You could write your own easily enough, but as already mentioned in the comments there's the Views Reference Field module which will provide the functionality.


How do I create a custom view filter for an existing field? I ran into a problem with creating a custom view filter for an existing field for Drupal 8. I mean a filter not for fields like "nid", "title" and so on, but for fields, which were named CCK-fields first.

Could you share with me an understandable example of code, how to create this plugin?

I tried to comprehend some examples in contrib modules, like the geolocation module, but that code was very sophisticated. Also, I haven't found adequate manuals anywhere.

If you do not need to code your Views filter, in your Articles View, you have a Filter criteria section where you may add views filters based on many different entities, including fields (what you call CCK fields)￼.


Returns 403 error after user login My site was copied from production to test server. It works on Drupal 7 + Nginx + PostgreSQL. On production, user login works fine, but on test server I receive a 403 error on users/admin (or user/1) where I'm redirected after login.

What I've already checked/done:

Database tables cache_* and sessions are empty.
User admin in the database has: uid = 1, status = 1, roles = 2 (authorized), 3 (administrator), 10 (site admin)
Try to open in IE, Chrome, Firefox. All history (cache and cookies) were deleted.
In file sites/default/settings.php there are the variables $base_url = "http://mytest.domain.com", and $cookie_domain = "mytest.domain.com"
nginx.conf contains such rules for 403 error:

location ~ \..*/.*\.php$ {
    return 403;
}

location ~ ^/sites/.*/private/ {
  return 403;
}

location ~ (^|/)\. {
  return 403;
}

Also all fastcgi_cache options are commented out.
Permissions on server: sites/default - 775 (folders), 644 (files); sites/default/files - 775 (folders), 644 (files).
Also I see that login field in the users table is updated when I login, but  the watchdog table and sessions table don't contain rows about the session being open.
php.ini: opcache.enable = 0

How can I fix the 403 error?

I've found a problem. As I said, I'm new to this project and recently I've found that it uses a Memcache module to save sessions. But both memcached and php5-memcached were not installed on my test server.


How can I pass the loop.index from a view template to a node template? In a views template (views-view-unformatted.twig.html), I have
{% for row in rows %}
    {% set row_index = loop.index0 %}
    {{ row.content }}
{% endfor %}

where each row is processed in a node--view.twig.html.  How can I pass in row_index to the node--view.twig.html?  This is used simply to create an index.

This can be done using the preprocess function in my_theme.theme.  In the case above, the row was formatted in node--view--pagename.html.twig, so the preprocessor function name is mytheme_preprocess_node__view__pagename.  In the function, the view is iterated until the node matches the current node that is being processed, at that point, the row_index is determined and set and accessible in node--view--pagename.html.twig as {{ row_index }}.

function fu_preprocess_node__view__pagename(&$vars) {
    $view = $vars['view'];
    $node = $vars['node'];
    foreach($view->result as $key => $row){
        if($row->nid == $node->id()){
            $vars['row_index'] = $row->index;
        }
    }
}


Display node with mixed languages My nodes, with entity translation enabled, need to be able to handle a node where the content of the node is displayed differently regarding the labels and menus.

Let's say I am on a french page, displaying a list of all nodes, translated into french or not. If I click on a non-translated projects url I need the node to be displayed in a french environment (menus and labels in french) but displaying the node in its original language.

Any idea how to achieve this?

This is more or less the default behavior, depending on your Languages Detection and selection configuration.

In Drupal 7 every translation of a node is a new node, with its own node ID. So when you call for that node it will be displayed (call it by node/[nid] or a path alias).

Interface language (menus etc) is calculated separately from content, by the Detection and selection settings (/admin/config/regional/language/configure).

The most common setting is to only enable the URL Detection method and configure your default language not to use the Path prefix language code or Language domain and set one for all the other languages.

This way if you have an English node and you want to open it with a French interface the link should be constructed as:

/fr/node/[englishID]

or

/fr/[french-path]/[english-title-pattern]

So whatever method you're using to display node lists you have to adjust their URLs output to follow that logic.


Circular Search view not returning results if city exists in UK AND elsewhere We have a locational search (using circular search filter in the View) available for our member groups across the UK: https://makingmusic.org.uk/resources/find-a-group-list

Entering cities/towns by name such as 'London' returns results correctly, but where there is a town/city with the same name abroad (e.g. 'Durham' or 'Cambridge' which both also exist in the US) no results are returned unless the country is included: 'Durham, UK' or 'Cambridge, UK'.

Since the search should only cover the UK (and so there shouldn't be a conflict caused by a place name existing outside the UK) is there a setting where I can limit the search criteria so that it only looks for places in the UK (and so doesn't get stuck where the name appears somewhere other than the UK as well)?

The Geofield proximity Views filter doesn't have any default location settings. The filter passes the given string value on through to the geocoder without any additional settings:

  $geocoded_data_raw = geocoder($geocoder_engine, $location);

As such, your only option is to form alter the submitted data as answered in this question:

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#submit'], 'MYMODULE_form_views_exposed_form_submit');
}

/**
 * Modify submission value with " UK" if given origin has been supplied.
 */
function MYMODULE_form_views_exposed_form_submit($form, &$form_state) {
  if (isset($form_state['values']['field_geofield_distance']['origin']) &&
      strlen($form_state['values']['field_geofield_distance']['origin']) > 0) {
    $form_state['values']['field_geofield_distance']['origin'] .= ' UK';
  }
}


Save my link configuration with drush or else? I just modified my database so I can translate 2 link from a block that I made.

The translation won't show up until I go here admin/structure/menu/item/1022/edit and press Save.

I would like to know if it's possible to do this with Drush or something else. Im in a Multisite environnement with more than 100 site, I would like to automate that task.

I tried to make a custom module to try and save my configuration but it doesnt seems to work.
I followed these steps : http://www.jpstacey.info/blog/2014-08-05/programmatically-creating-drupal-menu-link-item

Block translation is difficult, as mentioned also in this interesting article about Successful multilingual sites in Drupal7.

Maybe you want to consider using the BEAN module combined with the Entity Translation module?

PS: How make your Drupal website multilingual is another related article.


how to show more information in user's profile by default user's profile in drupal show very little information about users. I can extend that by adding more fields to profiles.
but I want user's profile in such a way that it would be showing all his/her information and some more information like users last 10 posted content, top 10 rated content and most commented content etc.

how can I extend this type of profile view in drupal?
please suggest me, thanks in advance :):)

For things like last 10 posted content, I believe you can use contextual filters in Views. With that you can create pages like /user/somebody/posts where Views will show you the last contents of user for example, also I believe you can make a block out of such a view that you can place on profile pages.

Also it may worth for you to check out the Profile2 module, you can create multiple types of profile pages with it for example.

http://drupal.org/project/profile2


Creating Preprocess function to add extra classes dependent on field value I have a content type called "article" and I have a field called "text color" and I want to add this text color field's value as a class to either the body or content container and change the text color of the content.

Which preprocess function should i go about using?
Is it possible to just do an inline style using the text color field's value so i don't have to also edit my css file too?
Or is there another elegant way of doing this without using a preprocess function?

You can add the class to the body from the node field value in hook_preprocess_html

Something like:

/**
 * Implements hook_preprocess_html
 */
function THEME_preprocess_html(&$vars){
  // Check if on an article node page
  if($node = menu_get_object('node') && $node->type == 'article'){
    // Get field values
    if($text_color = field_get_items('node', $node, 'field_text_color')){
      // Add first text_color value to body class
      $vars['classes_array'][] = drupal_html_class(reset($text_color));
    }
  }

}


Content types are missing in Features I am trying to create a Features module and include my content types but not all of them are showing when I select "Content Types: node".  I am seeing about 80% of them.  Why would this be?

If you are using a distribution, etc., it may be the case that there are content types that are provided by another feature or custom module.  These will not appear in the Features UI by default in order to prevent conflicts.


How to add the current title to the breadcrumb without preprocess function? I'm trying to get the title into my breadcrumb path without using a preprocess function. Drupal 8 Add the current title to the breadcrumb shows how to do it with preprocess function which is not what I'm trying to do.

I want my output be like this:

Here is what have been trying and have not work yet.

breadcrumb.html.twig

{#
/**
 * @file
 * Theme override for a breadcrumb trail.
 *
 * Available variables:
 * - breadcrumb: Breadcrumb trail items.
 */
#}
{% if breadcrumb %}

{{ 'Breadcrumb'|t }}

{{ 'You are here:'|t }}
            {% for item in breadcrumb %}

                    {% if item.url %}

                        {{ item.text }}
                    {% else %}
                        {{ item.text }}
                    {% endif %}

                {{ '>'|t }} {{title}}
            {% endfor %}

{% endif %}

And this is what I'm getting:

For some reason the title is not been display when I use {{ title }}.

What am I doing wrong?

Why is my title not being displayed on my breadcrumb title?

There is also an alter hook for breadcrumbs, where you can alter them in a non-theme specific way, in case the breadcrumbs are also used somewhere else.

I've implemented this in a project:

/**
 * Implements hook_system_breadcrumb_alter().
 */
function yourmodule_system_breadcrumb_alter(array &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  // Append the current page title to the breadcrumb for non-admin routes.
  if ($breadcrumb && !\Drupal::service('router.admin_context')->isAdminRoute()) {

    $title = \Drupal::service('title_resolver')
      ->getTitle($request, $route_match->getRouteObject());
    if (!empty($title)) {
      breadcrumb->addLink(Link::createFromRoute($title, '<none>'));
    }
  }
}

EDIT for Drupal 8.2.x

I add a lot of error with this code, which I believe is the best approach for altering the breadcrumb has seen on Drupal API.
So here is the code for Drupal 8.2.x

/**
 * Implements hook_system_breadcrumb_alter().
 */
function YOURMODULE_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  // Append the current page title to the breadcrumb for non-admin routes.
  if ($breadcrumb && !\Drupal::service('router.admin_context')->isAdminRoute()) {

    $title = \Drupal::service('title_resolver')->getTitle(\Drupal::request(), $route_match->getRouteObject());
    if (!empty($title)) {
      $breadcrumb->addLink(\Drupal\Core\Link::createFromRoute($title, '<none>'));
    }
  }
}


Why are we using utf8mb4_general_ci and not utf8mb4_unicode_ci? Drupal is moving to support utf8mb4, however, it is using utf8nb4_general_ci. Why take the time to move over to support it, and then not fully support it? Is there a specific reason, or just continuing utf8_general_ci from previous?

Would there be any problems with ignoring this and using unicode anyway?

Drupal Ticket:
MySQL driver does not support full UTF-8 (emojis, asian symbols, mathematical symbols)

Here is a question on stack exchange which says really there is no reason not to use unicode now days and finally, on this question, it says "utf8_general_ci is a legacy collation that does not support expansions, contractions, or ignorable characters."

I note that WordPress uses utf8mb4_unicode_ci.

It seems to me that the recommendation is outdated and that  utf8mb4_unicode_ci will work without problems. It has been used by a lot of people for a long time.

There is a difference between changing the character set from utf8 to utf8mb4 (to support more codepoints) and changing the collation from general_ci to unicode_ci (to get more accurate sorting). Both changes can cause their own problems, so doing both independently makes sense.

utf8mb4 is used by default since 8.0.0-beta12. The main issue seemed to be a change of key lengths limitations for InnoDB but as I understand it, utf8mb4 should have worked with the default MyISAM engine even before that change.

Switching to unicode_ci shouldn't cause problems, but may unexpectedly changes the order of sorting for some sites.

The default collation setting is just a default and modules can choose their own collations anyway if they need to. I also haven't found any documentation that says modules should expect a certain collation. The database install guide just lacks a clear statement about which collations are supported and is inconsistent:

In the section about phpMyAdmin it says that you have to

  Make sure you select COLLATION utf8_general_ci

Later in the section about installation from command line, general_ci doesn't seem to be required and any UTF-8 collation will do:

  Note: The database should be created with UTF-8 (Unicode) encoding, for example utf8_general_ci.

Furthermore, PostgreSQL is supported and it seems its default UTF-8 collation is equivalent to utf8mb4_unicode_ci, so using that with MySQL should be fine too.


Add trailing slash to taxonomy term. Issue with relative URL We were trying to create relative links by using href="Link" or href="./Link"

This works on all browsers, but in Drupal we are running into a problem becasue Drupal removes trailing slash from existing URL.

For example if we are at page or taxonomy term page

domain.com/term1/child1A

and in there have a link such as a href="Link" it will point to domain.com/term1/Link

becasue child1A does not have a trailing slash.

Is there any way to fix this issue. Technically we are not trying to add trailing slashes to all url. Tried setting base URL but that didn't work either. Or maybe I did something wrong.

Any suggestions on a workaround?

Drupal 8.4

The key to this answere is that the URL needs to end with a slash.

I turns out Redirect modules will remove trailing slashes.

You can disable clean URLs if you want trailing slash. Which is not ideal.

A workaround would be to use this code for particular links:

link

var x = window.location.href; // Current page URL
var link = document.getElementById("relurl"); // store the element
var curHref = link.getAttribute('href'); // Get HREF paramter
link.setAttribute('href', x + "/"+ curHref);


Create single exposed filter that does OR filter based on two fields D7 - Views 3 I have a content type teams and a content type games. Games has two node reference fields: home-team and away-team (that both reference content type teams). I want to create a single exposed filter teams that filters to games where either home-team or away-team matches the selected team.

For those with more experience hacking views - what approach would you take? Should I extend a handler to do this (views_handler_filter_in_operator)? Any pointers?

Or run a db_query and pass the results to a views alter hook?

Any input appreciated.

Views 3 views have a neat little semi-hidden feature. Click the arrow on the add button in the Filters section and pick and/or. From here, you can create filter groups and sort your filters to use AND or OR depending on your needs. Play with it; I think you'll be able to solve your issues like this.


Select from list or create other structured data in form field I want to let users choose from a list of checkbox items, and I want users to be able to build their own options, if the options they want aren't in the list of checkboxes.
I'd like users to have the ability to build as many "custom" selections as they'd like.

The value is compound, so http://drupal.org/project/select_or_other won't cut it.

Is there a good module for this or a FAPI approach? It seems like this is close.

Here's a pseudo interface for illustration:

Select:

[] 1 liter(s)

[] 2 liter(s)

[] 1 gallon(s)

[] 2 gallon(s)

Or other(s):

[  (textbox that accepts number)  ]  [ (dropdown that lets you choose liter(s) or gallon(s)) ] [Add] <--a button

You should check the examples module. Especially the ajax module. there is an example called Generate checkboxes This would lead you to the right direction.

The process would go as follows. You create the basic form then use create a button with Ajax call back. and return the required check box using the callback function.

This is the relavent function that generated the form.

function ajax_example_autocheckboxes($form, &$form_state) {
  // Since the form builder is called after every AJAX request, we rebuild
  // the form based on $form_state.
  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;

  $form['howmany_select'] = array(
    '#title' => t('How many checkboxes do you want?'),
    '#type' => 'select',
    '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
    '#default_value' => $num_checkboxes,
    '#ajax' => array(
      'callback' => 'ajax_example_autocheckboxes_callback',
      'wrapper' => 'checkboxes-div',
      //'method' defaults to replaceWith, but valid values also include
      // append, prepend, before and after.
      // 'method' => 'replaceWith',
      // 'effect' defaults to none. Other valid values are 'fade' and 'slide'.
      // See ajax_example_autotextfields for an example of 'fade'.
      'effect' => 'slide',
      // 'speed' defaults to 'slow'. You can also use 'fast'
      // or a number of milliseconds for the animation to last.
      // 'speed' => 'slow',
      // Don't show any throbber...
      'progress' => array('type' => 'none'),
    ),
  );

  $form['checkboxes_fieldset'] = array(
    '#title' => t("Generated Checkboxes"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('This is where we get automatically generated checkboxes'),
  );

  for ($i = 1; $i <= $num_checkboxes; $i++) {
    $form['checkboxes_fieldset']["checkbox$i"] = array(
      '#type' => 'checkbox',
      '#title' => "Checkbox $i",
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

There are couple of other examples related to the form api in the examples module that you can check out as well.


Missing Schema on custom field only during PHPUnit Test I have a custom field setup that I created similar to this tutorial. I exported all my fields on my node to a test module and enable it during my PHPUnit test.

I run my test with the following command:

php ./core/scripts/run-tests.sh --verbose --php /usr/local/bin/php --url http://nginx --class "Drupal\my_module\Tests\ExpenseTest"

And I get the following error:

The test did not complete due to a fatal error.
Exception Uncaught e ConfigSchemaCheck   95 Drupal\Core\Config\Development\Conf
Drupal\Core\Config\Schema\SchemaIncompleteException: Schema errors for
core.entity_form_display.paragraph.my_field.default with the
following errors:
core.entity_form_display.paragraph.my_field.default:content.field_city_state.settings.size
missing schema,
core.entity_form_display.paragraph.my_field.default:content.field_city_state.settings.autocomplete_route_name
missing schema,
core.entity_form_display.paragraph.my_field.default:content.field_city_state.settings.placeholder
missing schema in
Drupal\Core\Config\Development\ConfigSchemaChecker-&gt;onConfigSave() (line
95 of

This is part of my core.entity_form_display.paragraph.my_field.default.yml file:

field_city_state:
weight: 2
settings:
  size: '60'
  autocomplete_route_name: my_module.city_autocomplete
  placeholder: ''
third_party_settings: {  }
type: city_state_default
region: content

If I remove the settings it doesn't give me the error (Although I am not testing that field yet).

This is my module's Field Type Class:

<?php

namespace Drupal\my_module\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldItemInterface;

/**
 * Plugin implementation of the 'city_state' field type.
 *
 * @FieldType(
 *   id = "city_state",
 *   label = @Translation("City/State"),
 *   description = @Translation("An entity field containing city/state"),
 *   category = @Translation("Address"),
 *   default_widget = "city_state_default",
 *   default_formatter = "city_state_default"
 * )
 */
class CityStateItem extends FieldItemBase implements FieldItemInterface {

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'state_code' => [
          'type' => 'varchar',
          'length' => 2,
        ],
        'city' => [
          'type' => 'varchar',
          'length' => 255,
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['state_code'] = DataDefinition::create('string')->setLabel(t('State Code'));
    $properties['city'] = DataDefinition::create('string')->setLabel(t('City'));

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->state_code;
    return $value === NULL || $value === '';
  }

  /**
   * Get city string.
   *
   * @return string
   *   Returns city name.
   */
  public function getCity() {
    return $this->city;
  }

  /**
   * Get state code string.
   *
   * @return string
   *   Returns the state code.
   */
  public function getStateCode() {
    return $this->state_code;
  }

}

This is my module's schema file:

city_state:
  type: mapping
  label: 'City/State settings'
  mapping:
    state_code:
      type: string
      label: 'State Code'
    city:
      type: string
      label: 'City'

Don't understand why I am getting this error and only during Testing. (No issues when running config import on dev and staging).

You only get that error during testing because the core testing base classes add a config schema checker during testing.

You have 2 options, the first is the easiest, but is not recommended, and that is to disable the strict config checking in your test by setting this variable to false in your test class:

  /**
   * Set to TRUE to strict check all configuration saved.
   *
   * @see \Drupal\Core\Config\Development\ConfigSchemaChecker
   *
   * @var bool
   */
  protected $strictConfigSchema = FALSE;

This approach is not preferred because you then have invalid config schema data in your module. It would be far better to fix the schema.

Instead of city_state: in your schema file, something more specific like:

field.field_settings.city_state:

or since this appears to be display related, it might be

field.formatter.settings.city_state:


How do I add class "caption" into image? I using image field with insert module to upload image.
After select an image and upload, I press "insert".
The image appears in body but the script of image doesn't have class "caption".

<img src="/sites/default/files/apple.jpg" title="Some description image here" height="260" width="500">

How do I add class "caption" into image?

There is an option in the Insert section of the field to add classes. See the screenshot below.


Site re-directs to login page even after a successfull login Presently I am using the Windows Server on which the drupal 7.34 is installed with the xampp server.

The url for the site is localhost:8081/example

When I enter the URL(localohost:8081/example) to login, the page simply re-directs to the login page

Whereas when I enter the complete URL (the IP address along with the port number it loads the site)

Now I can't figure out why the page is redirecting me to the login page but not the main page when I am entering the localhost:portno/example

[update]

Things Tried:-

1.Pinged the IP address and it was successful with no loss.

2.Tried it on a different browser Internet explorer got Error HTTP Error 403 Forbidden.

3.Tried on a different system with the same IP address and in that system the site loads fine.

Re-installed the drupal software again with the same localhost:portno/

This behavior is normal

The default front page of Drupal is this one. It displays the latest published and promoted nodes. If you want to put another node as a front page you can do it in configuration>site information

Also drupal assumes that your site is in the top level directory (e.g. yourserver:port/)
If you want to change it to yourserver:port/custompath/ then set the $base_url to custompath in your settings.php file


Strip HTML tags from Field Collections in Services Views I'm trying to strip the HTML tags from a JSON response I generated using Services Views, but I'm not having any luck so far.
I have a content type with a Field Collections field in it that is outputting HTML tags no matter what I do.
I've tried the following:

Check Strip HTML tags in the field settings in the view
Set customize field HTML to 'None'
Set Customize field and label wrapper HTML to 'None'
All combinations of the above
Making sure to turn of all 'Provide default field wrapper elements' options

Am I missing anything? My output still looks like this in my json:

"Animals": [
            "
\n
\n

Animal:&nbsp;

Big

Withdrawal time:&nbsp;

25 dg

\n
\n",
            "
\n
\n

Animal:&nbsp;

Rund vlees

Withdrawal time:&nbsp;

21 dg

\n
\n",
            "
\n
\n

Animal:&nbsp;

Pluimvee ei

Withdrawal time:&nbsp;

6 dg

\n
\n"

Any help on this is greatly appreciated.

You have to tell use what you have done so far.

To strip tags use strip_tags php code. This function takes two parameters:

string strip_tags ( string $str , [string $allowable_tags ] )

The first argument is the string and the optional second parameter is to specify tags which should not be stripped. For example

<?php
    echo strip_tags("Hello world!","");
?>

Will output this

  Hello world!

Not

  Hello world!

I guess you have to use views_datasource module to generate JSON. I have already used this module and no default HTML tag were inserted by the View.

Did you try preprocess functions to strip the tags from the view?


How can I override certain breadcrumb segments? Drupal seems to be adding some default breadcrumbs that come from the URL.  How can I disable this feature? I don't see it in configuration but maybe I'm looking in the wrong place.

The default breadcrumb builder is defined in the system services file and has the priority 0:

system.services.yml

  system.breadcrumb.default:
    class: Drupal\system\PathBasedBreadcrumbBuilder
    arguments: ['@router.request_context', '@access_manager', '@router', '@path_processor_manager', '@config.factory',  '@title_resolver', '@current_user', '@path.current']
    tags:
      - { name: breadcrumb_builder, priority: 0 }

If you want to turn off the default breadcrumb builder you define one with a higher priority. This is an example for taxonomy terms:

taxonomy.services.yml

services:
  taxonomy_term.breadcrumb:
    class: Drupal\taxonomy\TermBreadcrumbBuilder
    arguments: ['@entity.manager']
    tags:
      - { name: breadcrumb_builder, priority: 1002 }

With the method applies() you choose for which routes the breadcrumb builder should be used:

TermBreadcrumbBuilder::applies()

  public function applies(RouteMatchInterface $route_match) {
    return $route_match->getRouteName() == 'entity.taxonomy_term.canonical'
      && $route_match->getParameter('taxonomy_term') instanceof TermInterface;
  }

The breadcrumb manager checks all applies() methods, starting with the highest priority, until it reaches the default breadcrumb builder, which applies for all routes:

PathBasedBreadcrumbBuilder::applies()

  public function applies(RouteMatchInterface $route_match) {
    return TRUE;
  }


Embed a contact form Is it possible to take a contact form and embed it into a page.html.twig or node.html.twig file? Or is the form only accessible via its contact/machine_name link?

Check out Contact Storage.

Among various other features, like being able to store contact messsages, the latest version has a view builder that allows to display a referenced contact form (it's a config entity, so you can reference it using a standard entity reference field).


How do I retrieve un-submitted values from a form and pass to another module? I have created a custom module called trim_users. What the module does is to alter the (menu) page callback of the user references module to execute a modified (by me) function of the user references module. The modification I've made is simple: I've altered a database query so that the users returned into my forms' autocomplete field is a trimmed down list of my users. I've joined on a 'user.team' field and I'm saying give me all the users where the team is 'x' and 'y'. So first the user enters the two teams into my form: team 'x' and 'y'. Then the user goes to enter a user. After the first character is input I want my trimmed list of users to drop-down in the autocomplete field.

I'm stuck on one bit: how do I send the values of team 'x' and 'y' sitting in my (as of yet unsubmitted) form so that the database query, in my trim_users module, can populate the condition clause with these two values?

Do I need to add an AJAX property to my form elements: 'enter team 1' and 'enter team 2' so that on change a function is called and the entered values made available to my trim_users module?

Thanks. Hope I explained that okay.

First, you shouldn't have to modify the page callback from the user references module. Instead, use hook_form_alter() (or hook_form_FORM_ID_alter()) to change the #autocomlete_path attribute of the user reference text box to point to you're callback instead. That way you aren't modifying the module's stuff and you have the option of using the default implementation somewhere else. This is generally a better option than modifying another module's menu items.

For your particular use case, you'll do what you actually suggested; use the AJAX properties on the team fields to make the information available to the autocomplete callback. In practice it's slightly more complex than that, but you've already got the right idea. There's an article on Active LAMP that does pretty much the same thing.

First let's see about your custom autocomplete callback. You need to know which teams (Team X and Team Y as you put it) to filter by and what string to search for. In the following code, you first create a menu item for your callback, then define the actual autocomplete callback. The menu item uses two wild cards in the path to provide the ids for Team X and Team Y to the callback. You do not need to specify a wildcard for the search string, Drupal will handle that for you. In your callback, use the id information to narrow your user query results.

function trim_users_menu() {
  $item['trim-users/autocomplete/%/%'] = array(
    'page callback' => 'trim_users_autocomplete_callback',
    'page arguments' => array(2, 3),
    'type' => MENU_CALLBACK,
  );
  return $item;
}

function trim_users_autocomplete_callback($x, $y, $string) {
  // Here, use the query you altered for finding the correct users.
  $query = <youre altered query>;
  // Now, return the available User options.
  // Taken from user_reference_autocomlete, minus the hyperlink removal.
  $matches = array();
  foreach ($query->fetchAll() as $row) {
    $matches[$row['title'] . " [uid:$id]"] = '
' . $suggestion . '
';
  }

  // return for JS
  drupal_json_output($matches);
}

Now you need to alter the form to make the user reference field use this custom autocomplete callback. The url you use for the user reference field's #autocomplete_path will follow the pattern of the menu item you create. Suppose you want to filter the users to Team X, with id 1, and Team Y, with id 2. You're path will be trim-users/autocomplete/1/2. To get  team ids for the path, you use #ajax['callback'] settings on the Team fields to respond to change events. For example, set the #ajax['callback'] property to trim_users_team_selected. When the Team field value changes, Drupal will rebuild the form then run your #ajax['callback'] to update the form on the client. So, inhook_form_alter()`, check if the team fields have a value, and if they do use it to build the autocomplete callback path you assign to the user reference field.

function trim_users_form_alter(&$form, &$form_state) {
  // Check if it's the correct form, or use hook_form_FORM_ID_alter instead.
  ...

  // Check the $form_state to see if there's a value for the Team fields
  if (isset($form_state['input']['field_name']['#value']) {
    // Get the value of the field and use it in the autocomplete callback path
    ...
  }
  ...
}

// Return the User Reference field element from the rebuilt form. This will
// replace the existing field element on the client.
function trim_users_team_selected($form, $form_state) {
  return $form['user_reference_field'];
}

There's a few other things you have to do, like set the #ajax['wrapper'] property, but that's all part of using #ajax['callback'] so I'm not going to get into that here. This should at least get you on your way, you just need to figure out the specifics of retrieving and setting the form field values.


Why is Twig not outputting this correctly? I have

function hook_theme_preprocess(array &$variables, $hook) {
    $variables['bla'] = ' AA <strong> BB </strong> CC ';
}

In my template I have:

{{ bla }}

The problem is, in some cases the  html is stripped. Even if I do this:

{{ bla | raw }}

This works fine on all pages where this template is used, except on the home page. On the home page, for some bizarre reason, it strips the HTML.

Any idea as to why there would be different behaviour depending on which page I am on?

It's unsafe to use the |raw filter. Put HTML markup in a #markup element instead:

$variables['foo'] = [
  '#markup' => ' AA <strong> BB </strong> CC ',
];

Then outputting this variable in Twig should work:

{{ foo }}


Why do modules have bug reports? A good question was raised in this comment by EGHDK:

  Why do these modules have bug reports. Shouldn't this be a simple task for a module to complete with no errors?

He was referring to limiting the viewing of pages to users of a certain role, but the question applies broadly.

There's a big difference between creating a custom module for just one site (your own, let's say) and creating one that will be able to be used on many different sites.

For example, let's say I want to limit access to a certain content type to only users of a certain role. Let's say that content type is 'awesome_thing' and the role is 'awesome_person'. There are two ways to go about this.

My own module that no one else will ever see or use

This would probably consist of something like a hook that gets called for each page, examines the $node object to see if it's 'awesome_thing' and then, if it is, examines the $user object to see if it's an 'awesome_person' and, if so, loads the page or whatever.

A module that is fit for contribution to d.o contrib

This would have to include a configuration interface that allows users to specify which content types they want to restrict, and which roles they want to allow on those content types. If there's more than one combination of role and nodetype then you have to deal with that. Then, since you've given a mouse a cookie, people are going to have feature requests, or maybe they'll write patches that add features and you think they're cool and you want to integrate them into a new version of your module.

Then say your module has a dependency on another module for some of these features, or your naming conventions conflict with another module's. On most sites this won't be noticeable so you probably wouldn't ever encounter it as a problem just on your own site. But by the law of large numbers, if you let a whole bunch of people use your module, they're more likely to discover corner cases where things work in unexpected ways than you are to think of every possible use case.

And then someone might look at your module and see that you violated a coding standard or namespace convention. Or they might see that you used 5 lines of code to do something that could be better done in 3 lines, or that you did something that's going to be expensive on performance if the module is used on a large-scale site with higher traffic than yours.

The tl;dr is that writing your own snippet for your one little use-case is exponentially less complex than writing, say, a patch for public consumption which itself is exponentially less likely than a full-blown module to both contain bugs and to have its existing bugs noticed and called out.


How can I import special characters using Feeds? I am using the Feeds module to import data into my site from a CSV file.

When I try to import a row that has the € character, nothing gets imported and I get an error message.

  error:General error: 1366 Incorrect string value: '\xE0 Cali...' for
  column 'message' at row 1

How can I import special characters using Feeds?

Consider using the Feeds Tamper module. Here is a quote from its project page:

  ... provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below. Additional plugins can be added in separate modules or through the issue queue.

It allows for HTML encoding / decoding of feeds content before saving.

PS: Feeds Tamper doesn't know anything about taxonomy terms (you cannot use it for "Terms", as mentioned in a comment to this answer, which the original question didn't mention though).


Executing jQuery code during form submission I developed a module to show an "End" button on the node edit form, and it works fine.

function renew_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['property_endlease'] = array(
    '#type' => 'submit',
    '#value' => t('End'),
    '#access' => TRUE,
    '#weight' => 15,
  );

  return $form;
}

I want that, when users click on that button, some fields are changed from jQuery code.

I tried the following code, but it doesn't show any alert, even though the form is submitted.

jQuery('#edit-property-end').click(function (event) {
  alert('');
});

I want to submit the form after the jQuery code is executed.

Does anybody have an idea on how to do this?

Thanks

Try this

   $form['actions']['property_endlease'] = array(
            '#type' => 'submit',
            '#value' => t('End'),
            '#access' => TRUE,
            '#weight' => 15,
            '#attributes' => array("onclick" => "javascript:test();"),

        );

and create a custom js

function test()  {
//your code
}

Hope it will work


How can I save 30,000 nodes in less than a day? Recently I have written a module that reads contents from a file; downloads associated image files; and then saves that to the Drupal 7 as a new node using node_save.  The script works fine, but the minute I start the script I have about 16 to 24 hours before it would finish all 30,000 entries. Yea, that's way too long.

What are some suggested design patterns for my module to finish this as fast as possible? Here is the current architecture:

$items = getArrayOfItems();    //reads file and gets an array of items
foreach ($items as item) {
    $node = new stdClass();
    $check_exits = check_title_exits($item[title]);    // note: call to database
    if(!$check_exists) {
        populateNodeObjectFields($item);
    }

    if($images = hasPhotos()) {    //note: must dl up to 4 images from web using CURL
        //create file object and apply to node image field
        $node->image_field = $images;
    }

    //do final custom validations
    validate($node);

    if($node = submit_node($node)) {
        node_save($node);    //note: call to database
    }
}

Everywhere I have a note I believe is a bottleneck. Here are my theoretical thoughts on improving the speed.
1) instead of checking against the database for a title (exists) load all titles into an array and check against the array
2) maybe I can separate the file downloads for a separate process to handle later after the node has been saved?
3) This is the biggest bottleneck.  If I am understanding the Drupal API correctly, this opens a connection and saves the node one by one - or more than 30,000 times. How can I just open up one call to the database and save all nodes in one batch?

My original solution was simply to have multiple scripts run simultaneously and be responsible for a certain chunk of the data. 12 scripts for example should have cut it down to 2 hours tops for all the data.  The problem with that is I keep getting PDO exceptions - serialization errors.  Please see this link where I wrote about it. PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock;.  If I could fix that, I would be happy to continue with that solution.

Thoughts on the best way to approach this?

I think you should have a look at the migrate module. I have used it to create 60k plus nodes via xml in less than an hr. It has a learning curve attached to it but the examples are good and it will import in a clean and proper manner.

Also it has command line integration with drush so you do not run into timeout issues.


Render view in specific language How to render view in specific language?

$view = views_get_view("commerce_line_items_custom");
////Pass arguments
$view->set_arguments(array($data['commerce-order']->order_id));
$view->hide_admin_links = TRUE;
////Generate content
$content =  $view->execute_display('block');

I tried following overide, but it did nothing:

$view->set_display('block');
$view->display_handler->options['field_language'] = 'fr';
$view->display_handler->display->display_options['field_language'] = 'fr';
$view->display_handler->default_display->options['field_language'] = 'fr';
$view->display_handler->set_option('field_language', 'fr');

May be you can try this.

function yourmodule_views_pre_render(&$views) {
  if ($views->name == 'yourviewname') { //yourviewname is the machine name of the view
    $_SESSION['language'] = fr;
  }
}


How to use trusted contacts as a selection rule for user panel page, drupal commons In Drupal Commons, using Panels, I'd like to change the behavior of the user page.

One variant for users to view their own page, and another for viewing other user pages.
Also, I'd like to limit it so that only the trusted contacts of a user can view his/her page.

It is set up using panels, so first I added a variant with a selection rule: user: compare - User being viewed is not Logged in user. This works fine.

But how to configure it to limited to trusted contacts of a user.
The context for  user: user_trusted_contacts is already listed as an option, but I can't use it as a selection rule. There's no option there for "..user is one of".

I'm sure it can be done within panels, thanks for any help.
D

commons-7.x-3.46

I couldn't find a direct solution for this.

So as a workaround, I'm using Flags and Rules. Trusted contacts are flagged (explained in "How to create a rule to flag users when they're approved as a Trusted Contact?").

Once the flag is there you can then use it as a selection rule in panels.


How to add condition in between fields in Profile2 module in drupal 7? I am using the Profile2 module.
Two fields are there in the Registration Form i.e.

I am : [Baby Male, Baby Female, Daddy, Mummy]

&

Looking For : [Baby Male, Baby Female, Daddy, Mummy].

if user click on I am : [Baby Male] then in Looking For: [Baby Female] is only show.

If select I am : [Baby Female] then in  Looking For: [Baby Male].

So If I am : [Daddy] then in  Looking For: [Mummy] & If I am : [Mummy] then in  Looking For: [Daddy].

How can I do this?. Is there any module in Drupal 7?

Yes you can do this also option wise using field conditional state module.

Go through this field_conditional_state for details.

Trigger a state when applied to a control field:

    empty - Triggers when the control field is empty
    filled - Triggers when the control field is not empty
    checked - Triggers when the control field is checked
    unchecked - Triggers when the control field is not checked
    value - Triggers when the control field's value is equal to a given string
    !value - Triggers when the control field's value is NOT equal to a given string


Encoded strings in hook_menu wildcard case menu item to lose access I'm trying to create a menu link within the admin area that includes a urlencoded() copy of the current URL as a tail to the link URL, so that the code invoked can redirect back to the current page when it's done its job.

However, as soon as the string returned by my _to_arg() callback contains a URLencoded string (Or specifically any string containing a % character), Drupal drops access rights to that menu, and the link is hidden.

Sample code below:

/**
 * Implements hook_menu().
 */
function admin_bar_menu() {

  $items['admin/bar/%test'] = array(
    'title' => 'Admin Bar Test',
    'page callback' => '_admin_bar_redirector',
    'page arguments' => array(2),
    'access callback' => 'user_access',
    'type' => MENU_NORMAL_ITEM,
    'weight' => 15,
  );

  return $items;
}

function test_to_arg ( $arg, $map, $index ) {

  // 1. Link is shown, but is of the form /admin/bar/admin/appearance,
  // so the desired string (admin/appearance) can't be retrieved
    // return $_GET['q'];

  // 2. Link is hidden
  // return urlencode($_GET['q']);

  // 3. Link is hidden
  // return 'foo%bar';

}

function _admin_bar_redirector($destination) {
    drupal_goto($destination);
}

I'm pretty sure this is being caused by the following code in menu.inc (Line 911 - d7.14):

// Skip links containing untranslated arguments.

if (strpos($item['href'], '%') !== FALSE) {
  $item['access'] = FALSE;
  return FALSE;
}

Can anyone suggest a potential avenue for a fix to the code in menu.inc - or is there a better way to achieve what I'm trying to do?

I've assumed this needs fixing in core, so logged it here - any insights welcome!

http://drupal.org/node/1822004


How to disable/hide /unset a block programatically? I have a page whose content is visible only in certain provinces. When people visit this page from a different province other than the one it is set for,it should be giving a message saying "the content is not available in the region" by overwriting the node's body in the same page, by using hook_node_view. But I have blocks enabled in the content area on this page. is there a way to disable the contents of the block? i tried hook__block_view and hook__block_view_alter but it did not work. Can someone help me?

You could try hook_block_list_alter to hide a specific block.

Act on blocks prior to rendering.
This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.


When creating a new user with a order, how to email the new user login details I am using Commerce Admin Order Advanced. It allows the following extras when creating an order in Drupal Commerce

Search users by email or profile name before creating the order
Select existing customer profiles before creating the order Validates
Check a new customers email against existing customers to prevent duplicates
Moves customer profiles to the top of the admin order form
Provides copy address profile functionality on the admin order
interface (uses the same settings as the checkout pane for this
feature)

But it also will create a new user with an order, however there is no email sent to the new user with a one time link to login and set a password.

Does anyone know how this could be achieved?

I have achieved this using Rules

The Rule is as follows.

Events
After updating an existing commerce order

Conditions
Data value is empty - commerce-order:owner:last-login

Actions
Send account e-mail

The reason why I have used this Event rather than 'After creating a new order' is to do with how this 'Commerce Admin Order Advanced' module works. You create the order before adding line items. And since I only need this email to be sent when a certain product type is created, this should suffice, hence I add the following condition

Order contains products of particular product types - Bespoke (an arbitrary product type)

But in order to prevent these emails being sent again should an admin update the order again, I have added the following extra Condition

Data comparison - commerce-order:created == commerce-order-unchanged:changed


Query - Content type I want to get all created content of some content type by query. By now I can access nodes by their ID.

$MyNode = \Drupal\node\Entity\Node::load(1)

I tried some query, but none of them worked for me. Maybe wrong conditions. My content type is 'beacons'.

$query = \Drupal::entityQuery('node')

Cant find it in my d8 book too.

The following should suffice:

$query = \Drupal::entityQuery('node')
  ->condition('type', 'beacons');
$entity_ids = $query->execute();

Here is a drush one-liner to test this on my D8 instance, where I have one article node:

 drush ev "var_dump(\\Drupal::entityQuery('node')->condition('type','article')->execute());"

Gives me:

array(1) {
  [101]=>
  string(3) "101"
}

where 101 is the nid of the article node.

Good luck!


How to correct disappearing admin menu? I use the Admin Menu module for my projects. In my Drupal 7 and Pressflow 7 instances, it randomly shows only some menu items.

At first, I thought I could correct this by clearing menu cache. When I went to the front page, I once again got the corrupted menu.

How do I solve this error, permanently?

I found out this issue is reported in detail, but there is only a workaround (disable menu caching).

I disabled menu caching with drush vset admin_menu_cache_client 0 as a workaround.
(I am still testing this issue with the menu cache enabled.)

I checked and eliminated JavaScript errors using Firebug browser extension.

I removed BOM from *.js files as suggested in this answer.

Add this to the bottom of your settings.php file:

$conf['admin_menu_cache_client'] = FALSE;


Rules won't let me change some node properties I am trying to create a new rules component (action set) for publishing content that has been unpublished and I cant seem to set a few of the node properties. I will either use Flag or Rules Link to fire off the action set.

The main goal of changing these values is to basically reset the node as if it was just created, without having to make a new node and copy the field data over to the new node.

A node should become unpublished then when it is made published again, it should behave if it was a new node that was just saved. Created date is set to "now". Marked as "is-new", etc...

I can't change the node:is-new setting to mark it as new content again.
I also can't change the node:created or node:updated properties to change the date it was either created or updated. I just get a error that says "The selected data property doesn't support writing."

Any thoughts or work arounds for this?

You appear to be attempting to break the rules regarding node creation.  You could probably do it by writing a module but why?

If all you want to do is have a fresh copy of a node with similar field values, consider using Node Clone which is a re-write of one that used to exist called "Edit As New", apparently.  Or maybe Replicate.


How to enable PHP in a field? I have created a content type in Drupal 8 and I added a field named "body". But I'm unable to use PHP code in this field.

How can I enable PHP in my "body" field?

Using PHP in your body field is considered bad practice. Read: What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?

Even in the module page it clearly says:

  Warning

  Enabling this module can cause security and performance issues as it
  allows users to execute PHP code on your site. There are better
  alternatives out there that do not expose such vulnerabilities on your
  site.

The proper way to add your PHP:

Use a preprocess function in theme_name.theme located in your theme's folder.
Create a custom module that uses hooks or preprocess functions.

Furthermore, Twig has several filters and functions that you can make use of. Which in some cases, you don't even need to use PHP at all.


How to add a tab to shop pages? I'm on Drupal 8 with Commerce 2.

I created a view page to display the list of products in the stores.

Here is the way of my sight :

/store/3/produits

Can not add a tab to shop pages.

I am desperate.

Can you explain why the "Edit" tab on the page is missing ?

Here is my view, it is very simple :

Here is my page "Produits", there is no tab :

UPDATE: install Commerce Multistore module and have store/ID/edit, store/ID/products, user/ID/stores views tabs created by default for you

UPDATE: Add store/ID/edit, store/ID/products, user/ID/stores views tabs

Tabs can be automatically created for you by Views.

WDTutorials video: Tabs With Views in Drupal 8

You have to create a views' page having /some-path  which lists some entities (nodes, fields or products as in your question). Then you need to make it a Default menu tab (parent menu tab). So, if no any child tabs are present then the content for this tab will be displayed. It might be seen a bit confusing but you should choose Already exists option while creating this (newly created) menu tab. After that just create as many duplications of this page as you need and choose for each duplication a Menu tab option (child menu tab). Again, you might be confused which menu or menu entry to choose for children menu tabs. Actually, it does not matter a lot. For your view you may choose Products entry though <Main navigation> menu might be also a good choice. Do not ignore weight option assigning a proper value for each child tab. It helps to place tabs in the exact order you want. Leave 0 weight for the parent tab increasing it by 1 for each next tab.

Then, edit the path so it looks like /some-path/child-1 and add a filter criteria for a child tab (page). In the video the filter criteria is a node's published/unpublished status and in your case it should be a store ID. The ID of a particular store might be found on the /admin/commerce/stores by hovering over a store's Edit tab.

See more on the relative drupal.org issue:
https://www.drupal.org/node/2880510#comment-12185171


How do I get the current path and add a condition in page.html.twig? I have the view page called "location/all" which contain all the map details.

I changed some CSS styles.

{% if 'location/all' in url %}

{% else %}

{% endif %}

I tried this code to check the condition, but every time it executes the else part.

Try this

{% if 'location/all' in url('<current>')|render|render %}

Alternative solution would be to add the following to your THEMENAME.theme

function THEMENAME_preprocess_page(&$vars) {
  $vars['path'] = \Drupal::service('path.current')->getPath();
}

and use this in your page.html.twig

{% if 'location/all' in path %}


How to allow content tagging by anonymous users? I have a site, where the main purpose is the involvement of the public in their history. However, we all know some just don't want to register for a user profile with websites. In our case, there are some who would like to participate in tagging photograph nodes, without having to register.

So that is my question: how to allow anonymous users to tag photographs how they see fit, along with the obvious review process that would need to take place just in case? I've seen this feature on other sites, and have tried to contact the web admins, but have yet to hear back.

I know there is the module "Community Tags" and that works all fine and all but there are currently two problems I see with it (and if you know a solution that is staring me in the face, please let me know):

The anonymous users are allowed to post, but there is no review.
The tagging by the anonymous user does not sync at all with the only term reference field in the content type, so if I type one tag into one, it won't show up in the other. Both will post correctly to the list of taxonomy terms, but won't sync for the same page.

Any solution to my problem? Or maybe even an entirely better way of doing this altogether?

You could use the Flag module, and allow it to be used by anonymous users also, as described in my answer to "How to display a flag to anonymous users?". Create a flag for each tag you want to allow for anonymous tagging, and assume you label such flag like "Tag with TagABC".

Use the Rules module to create 2 Rules Components:

a 1st Rules Component (say "Approve Tag suggestions") that performs 2 Rules Actions, and looks like so:

apply the tag TagABC
unflag it again (to remove the flag "Tag with TabABC").

a 2nd (similar) Rules Component (say "Reject Tag suggestions") to only unflag (=remove the flag "Tag with TabABC") anything that is considered as "rejected".

Use the Views Bulk Operations (VBO) module (which depends on the Views of course) to create a VBO list of anything flagged like "Tag with TagABC", and use this during your review process to mark (select) anything that was flagged and that should be considered as "approved" (similar approach later on for anything to be considered as "rejected"). The actual "operation" to be performed (by VBO) is to execute either of both Rules Components described above. For more details on how you can use VBO and Rules together, refer to my answer to "How Do i implement an alternative for the Privatemsg Bulkmail module?".

4 commonly used modules (which can be used for plenty of other use case), and some relatively easy site configuration to be performed. That's it.

Limitation: what is above does NOT support FREE tagging (= invent your own new tags) for anonymous users (which may lead to tons of tags, used only once). Maybe a compromise could be to have a link to "suggest your own tag", via some form shown on a block? Other idea (never tried): flags are fieldable, so add a select list field to an extra flag (say: "pick your flag"), and use the "Select (or other)" module to allow such additional tag to be suggested.


"Valid date is required for date_1" error while using drupal_form_submit() Field : field_date_1
Type : Date
Widget : Pop-up calendar
The settings for date field is as shown in 2 images

I get the values of a form_state into the $source_node and move that to $fs variable.The $source_node has date field stored as follows :

 [field_pt_date_1] => Array
        (
            [und] => Array
        (
                    [0] => Array
                        (
                            [value] => 2010-08-27 00:00:00
                            [timezone] => America/Phoenix
                            [timezone_db] => America/Phoenix
                [date_type] => datetime
                        )
             )

)

 $fs['values']['field_date_1']['und'][0]['value'] = date('m/d/Y', strtotime($source_node->field_date_1['und'][0]['value']));
  $fs['values']['field_date_1']['und'][0]['timezone'] = $source_node->field_date_1['und'][0]['timezone'];
  $fs['values']['field_date_1']['und'][0]['timezone_db'] = $source_node->field_date_1['und'][0]['timezone_db'];
  $fs['values']['field_date_1']['und'][0]['date_type'] = $source_node->field_date_1['und'][0]['date_type'];

.........
The errors I am getting after executing the above code is as follows :

A valid date is required for date_1.

 drupal_form_submit('form_id', $fs, $source_node);
  $errors = form_get_errors();

And when checked the $errors variable I get

$errors = Array
(
 [field_date_1][und][0][value] => A valid date is required for date_1.
)

I was facing similar kind of problem with drupal_form_submit.

After spending too much time following solution is working for me

    $datetime = $source_node->field_date_1['und'][0]['value'] ;
    $form_state['values']['field_date_1']['und'][0]['value'] = array(
      'date' => date('d/m/Y', strtotime($datetime)),
      'time' => date('h:ia', strtotime($datetime)),
    );

Hope it will help someone


Adding a span tag to main menu items Possible Duplicate:
  How do I insert a <span> </span> tag inside the <a> </a> tag on my main menu

I tried the code found in How do I insert a <span> </span> tag inside the <a> </a> tag on my main menu, and I have a problem with it: while it does add the span tags, it also strips out the main menu's unordered list and classes.

How do I add the span tags inside the main menu links while also keeping the unordered list and the list menu classes?

Try this, http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_links/7:

function THEMENAME_links__system_MENUNAME_menu($variables) {
  $output = '';
  foreach ($variables['links'] as $link) {
    $output .= l('
 $class)) . '>' .''. check_plain($link['title']) .'' . '
', $link['href'], $link);
  }
  return $output;
}

Is the
 inside the ?


How to change the link in the view by content type? I change my question. Content type: How to add link field?

yes you can add the Link field by add a module called link module which will add a type called link in the add field drop down. for that you will need to install Link module

Hope this will help :)


Updating Drupal modules via git on remote server Here is my Drupal workflow for updating modules.

I update modules on my local dev and test.
Run update via drush if needed.
Commit and push to github.
Pull these new updates from Github on remote server to live site.
run update via drush.

However, I was thinking of making a "modules-update" branch, pushing to that from local dev, pulling that branch to my live site and merge with my master branch later if all went well. If all does not go well for some reason on the live site, then I could simply pull from my master branch that had the older versions and do a restore of the DB from the backup and restore module if need be.

So my questions is, I am looking for feedback if this seems like a sound practice or are there better ways to do this? I am fairly new to Git so I am guessing there might perhaps be a better way than this.

In my opinion the workflow you mentioned look good. You just need to make sure you have a latest database backup in case you need to revert back.
Have you looked into https://getpantheon.com/ it is free for drupal development. Request an invitation code at https://getpantheon.com/request-code Best thing about pantheon is it provides dev test and live sites, daily, weekly, monthly and on demand backups. Push code from dev to test and live, Pull database and files from live to test and dev with just push of a button.


How to show/hide the prefix/suffix for fields? Sometimes in theming I want to programmatically hide the prefix or suffix of numeric fields. How can I do so?

When you look at the code of the numeric field formatter:

NumericFormatterBase::viewElements

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    $settings = $this->getFieldSettings();

    foreach ($items as $delta => $item) {
      $output = $this->numberFormat($item->value);

      // Account for prefix and suffix.
      if ($this->getSetting('prefix_suffix')) {
        $prefixes = isset($settings['prefix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $settings['prefix'])) : [''];
        $suffixes = isset($settings['suffix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $settings['suffix'])) : [''];
        $prefix = (count($prefixes) > 1) ? $this->formatPlural($item->value, $prefixes[0], $prefixes[1]) : $prefixes[0];
        $suffix = (count($suffixes) > 1) ? $this->formatPlural($item->value, $suffixes[0], $suffixes[1]) : $suffixes[0];
        $output = $prefix . $output . $suffix;
      }
      // Output the raw value in a content attribute if the text of the HTML
      // element differs from the raw value (for example when a prefix is used).
      if (isset($item->_attributes) && $item->value != $output) {
        $item->_attributes += ['content' => $item->value];
      }

      $elements[$delta] = ['#markup' => $output];
    }

    return $elements;

You see three things, first this is fully configurable, so it has not to happen in the first place, second it's hard to change afterwards, because the field content and the prefix/suffix is concatenated into one string and third you can get the raw values without prefix/suffix from the items attribute content:

field--field-number.html.twig

Field raw values:

  {% for item in items %}

{{ item.attributes.content }}

  {% endfor %}


Change default upload file path (sites/default/files) for a content type Drupal default file upload path is sites/default/files.
How this default path change for a particular content type?
Consider an example..
My drupal installation directory is ../drupal then all the files
uploaded in inside location ../drupal/sites/default/files
I have created a content type "test", I would like upload all test content file in the location
../drupal/test

The public filesystem is a system-wide setting; it can't be different per content type.

There's a setting under every file field attached to your content types that will allow you to choose the sub-folder within public:// that files for that field are uploaded to.

As an extension you can get a more advanced version of that functionality with the File (Field) Paths module...but beware, there are issues with it and you'll need to test thoroughly before deploying to a live site.

One of those methods will likely be your best bet. There's lots more info at Working with Files in Drupal, including documentation on how to use the private file system (in case you can leverage that).


You might try compressing the data before sending it. There's a module for that: compressed_cache


Drupal 8 node serialization to JSON I am trying to use \Drupal\node\Entity\Node::load($nid) to store a node object in a variable and pass the variable into drupal 8's serialization component or even symphony's serialization methods. All my efforts have resulted in a JSON object that is only encoding the first property of the node which is {"in_preview":null}.

For example the following callback returns {"in_preview":null}

public function page(){

  $nrm = new \Drupal\Component\Serialization\Json;
  $node = Node::load(2);
  $json = $nrm -> encode($node, 'json');

  return $json;

}

What class/method would accomplish serialization of $node in the above code?

You should use the serializer service if you want to serialize a Drupal data type (Typed Data API) so that normalization is run properly. This requires enabling the serialization module as pointed out by Alari Truuts, which defines the serializer service.

The serialize method is a little confusing as to what the $context parameter means. For Drupal Typed Data, it requires the plugin id of the data type (EntityAdapter in this case).

$serializer = \Drupal::service('serializer');
$node = Node::load(2);
$data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);


Show content with a date after the current one on a view I'm creating a calendar of events with Drupal 7 using views. At the moment the elements are shown in order of the date of each one (I have a date field where I put the date of the event). Now I need that when the date is passed, it does not appear anymore.

For example, if I have an event that was held yesterday, today it would not have to appear in the view.

Thank you!

Just add a filter based on the date field and the criteria should be "greater than or equal to", then select "Enter a relative date" in the drop down field and enter the word "now"

Here is a screenshot from a site that has a Register By date field and I have a list of Upcoming Events that show based on this in a homepage block.


How to append fields to published node in drupal? A node once published should not be edited, but extra fields can be added to that node. How can i do it? For example , lets say i have a content type called 'employee'. Once i create this content i cannot edit that node but can only add more information to that node. this extra information must be stored in the node's column. Is it possible ? or is there any other way?

guess its possible with a combination of hook_form_alter and hook_nodeapi

Do check out these methods... hope it helps...