How to change the numbering in duplicate path aliases? All my node paths have a URL alias, provided by Pathauto. The pattern is [node:title]. The generated aliases for nodes with the same title are by default

title,
title-0,
title-1,

etc. I would like to change this numbering into

title-1,
title-2,
title-3,

etc. So, when a node with the title Test is submitted, a URL alias test should be generated. Once a second node with the same title is published, another alias test-1 should be created for the first node and a new alias test-2 should be added for the newly created node.

How can I do that?

pathauto_alias_uniquify(&$alias, $source, $langcode) is the function that does the suffixing to generate uniqueness. It has a hard-coded value that starts at 0.

However, Pathauto evokes a hook, hook_pathauto_is_alias_reserved() when it checks for uniqueness when generating its path alias. If you have a custom module evoke this hook, you can check reject instances of the -0 suffixing and tell pathauto to move onto the next entry.

/**
 * Implements hook_pathauto_is_alias_reserved().
 */
function MYMODULE_pathauto_is_alias_reserved($alias, $source, $langcode) {
  // Return FALSE when the alias ends with '-0'
  $zero_suffix = variable_get('pathauto_separator', '-') . '0';
  return (substr($alias, -strlen($zero_suffix)) == $zero_suffix);
}

This might catch entries that legitimately have "-0" in the path, but I'll leave to the reader to devise a workaround for that scenario.


Rules setup for Drupal Commerce I need to setup a rule on the drupal commerce with the following condition.

If Authenticated user added an item in cart and they didn't do the checkout for 24 hours, the site needs to shoot an email to the user with the cart content after 24 hours but only once, dont need to spam in every 24 hours.

How to perform this using rules? Any ideas Champs!!

Thanks

Try the  Commerce Order Reminder. It can help you!!

  As the name implies, this light weighted module sends email reminders to website users of the orders that were left uncompleted. The reminders will only be sent about those orders that have the email property filled. This includes even those orders of anonymous users that entered their email in the billing information form but did not complete the checkout process.


Theme Simplenews with MailSystem I would like SimpleNews use another theme (Bartik for example) than the admin one (Seven). I configured MailSystem to use "Bartik" as theme to render emails, as written in SimpleNews README.txt:

  The template files are self documented listing all available variables.
    Depending on how the mails are sent (e.g. how cron is triggered), either the
    default or the admin theme might be used, if one has been configured.
    To prevent this, Simplenews supports the mail theme setting from the
    mailsystem module (http://drupal.org/project/mailsystem). Install it, choose
    the mail theme and the newsletter templates from that theme will be used no
    matter which other themes are enabled.

In the simplenews.module file, I got the line:

2674.  $theme = function_exists('mailsystem_get_mail_theme') ? mailsystem_get_mail_theme() : path_to_theme();

And $theme is evaluated as "theme/bartik". Great, but it keeps use the "simplenews-newsletter-body.tpl.php" file in "theme/seven" directory.

I struggle with that for weeks now, any help would be welcome!

Thanks.

You do have the template files in themes/bartik*? Make sure to rebuild the theme registry.

This feature is relatively new but we've used it several times for ourself now and have multiple confirmations from other people that it works for them.

Note that the only thing that "using a theme" means is the place where Simplenews looks for the template files. Additionally, Mimemail also looks for for either the css files to embed or the mail.css (Hint: Older versions of Mimemail have their own setting, switch to the most recent dev version of Mimemail to get that fixed).

It does in no way take over the look and feel of your website, if you're looking for that, have a look at HTML Mail.

*Hint: You should not alter a core theme or add files into it, instead, create a subtheme and put that in sites/all/themes. Try Google to find more information about subthemes.


Load a node content programmatically How can i load the user page (profile) in a block or in the body of a another page?
I tried to put a block in the user page but does not work.
Any ideas?
Thanks.

You can print the user profile using:

<?php print render($user_profile); ?>.

You can get specific user information by

<?php print render($user_profile['user_picture']); ?>

<?php print render($user_profile['summary']); ?>

Hope this helps.


How to prevent 'drush up' from deleting non native inodes in a sub-theme folder? I installed the theme Basic, did drush up, updated this theme, and BAM, the sub-theme folder I created was deleted.

Gladly, I restored most of it, but why would drush actually delete any non-native folder when it's updating my theme?

Is there something to do to prevent drush from deleting non native inodes in a folder?

If your sub-theme folder is inside the base theme folder, it will get wiped out when there is an update to the base theme, as drush will remove the contents of the theme folder and replace them with the new updated contents of the theme.

The solution is to move the sub-theme folder to be along-side the base theme folder, so it's a sibling, rather than a child.


How to put google analytics script PHP to my sites? I apply a Google analytics service. I got a code.

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'MY UA CODE', 'auto');
  ga('send', 'pageview');
</script>

My drupal use AT Commerce this theme. Where do I put this code to my folder's file? There is an optional method. The php is here where I want to add to my block and let it call the above script.

<?php include_once("analyticstracking.php") ?>

Do I follow the same name analyticstracking.php or just add the above script to an existed php file? Thanks.

You can install module Google Analytics. Or paste script to file html.tpl.php.


No working link to network files For an intranet solution I would like to add a bunch of rather static links in Drupal to network files which change from time to time and are maintained by people not using Drupal.

To achieve this I used the link functionality of CKeditor:
Protocol
URL      file:///s:\Gloss.xls
target   popup window

When I throw file:///s:\Gloss.xls into any browsers address field it works perfectly (tried in IE, chrome and firefox) but from a Drupal node clicking on the link explained above, the browsers inspection reveals Not allowed to load local resource: file:///s:\Gloss.xls in chrome and firefox, only in IE it works.

What do I need to do to get it working in chrome or, at least in firefox?

I think the trouble comes from your browser. See the answer from this question :
How can I create a link to a local file on a locally-run web page?

  Some browsers, like modern versions of Chrome, will even refuse to
  cross from the http protocol to the file protocol, so you'd better
  make sure you open this locally using the file protocol if you want to
  do this stuff at all.

Maybe another approach is to make a script witch will get the file from the server side and send it to the client in streaming.


Documentation for the API exposed from Pressflow Reading How do Pressflow Drupal sites handle user Cookies? I discovered that Pressflow 6 has a function that is not present in Drupal 6, but that is defined in Drupal 7; although, the code used by Pressflow 6 is different from the code used by the homonym function in Drupal 7.

Should developers use only the functions that are defined from the equivalent Drupal version (e.g. Drupal 6 for Pressflow 6)?

Pressflow is designed to be API compatible with Drupal. As a consequence you should only use the API functions of Drupal 6 when developing for Pressflow 6.


Set data (current nid) to entity reference field with rules and VBO I'm currently stuck in the creation of a custom rule.

I would like to show a button on some content type, this button called a list of other content called "guide". I list these contents (guide) in a view and I added a field to associate a rule vbo.
In the type of content I have a guide entity reference fields might add my id of the current node content (the button add to the guide) to guide one or more listed.

How to perform the action:

get the nid of current content
define the fields at the end of the reference entity or selected guides
save the guide(s)

Note : The list of guides is showed in a lightbox when button "add to guide" in a content was clicked.

Thank you very much in advance

I will first confirm if I understood this correctly.

You have a content type where you will show a button. Let's call this content type MainType.
You have another content type called guide.
You have an entity reference field on guide which points to a particular node (nid) of content type MainType.
In nodes of MainType, there is a button which shows all guides pointing to the visible node. You already have this view.
You want to add a link which will create a new guide node with entity reference pointing the node on which the link was clicked.
From your comment: You want to use VBO to set referenced field in selected guide nodes to the current node.

I can't think of a way to do this without code, as the context of the original node is probably lost in the view of guide nodes. However, you can do it in a slightly different way:

Create a Rules component with two variables, both of Node type. First one is your guide node, set by VBO and the second will be your reference to the node.

You should then write your rules actions to set entity field value for guide node's field to the nid of second reference. You can take a look at this video which implements a very similar requirement.

I hope this helps.


Display the content of particular content type in side a block? I tried to create a block called contact details. I already created a content type called contact. I wanted to add the content of each contact content type in my custom block. I researched a lo abd I'm confused.

Install and enable the Views module.
Create a view with 'Block' display.
Filter by content type 'contact'. You can also choose sort options, etc.
Go to the Blocks administration page at Administration > Structure > Blocks.
Enable the Views block.


Block with the same function as page of Taxonomy term view Is there any way to replicate as block which displays all nodes associated with the end of the url, like page view ( Taxonomy term view -A view to emulate Drupal core's handling of taxonomy/term.)  but in a block.
Example in url news/term1 the block should be able to show all nodes with the term term1.

Thank

Set up a new view of type "node"
Give the view a "block" display (not a page)
In the "advanced" section of the view (on the right) create a relationship to "taxonomy term"
you can set up a "contextual filter" based on "taxonomy term".
The trick to making this work with a block is to select the "Provide default value" option and select "raw value from url" "path component 3". This will send in the id of the parent term from the url (works even though your term is aliased).
Go to admin->blocks and put that block in the "footer" region; set it to only appear at the url taxonomy/term/* (this will work even though your term is aliased).


How do I echo the node vocabulary in preprocess_page or in page.tpl.php so that I can test against it in Drupal 7? I need to be able to echo the vocabulary that is associated with a node, but I need to echo it either in the preprocess_page function in template.php OR somewhere in page.tpl.php. I can't seem to find how exactly this will work in Drupal 7. Does anyone know?

If you want to output something on in the page structure (ie. somewhere in page.tpl.php), you need to output it as a block, Drupal's primary structural element.

In a module, define a hook_block_info() (or hook_block() in Drupal 6 and below), and implement it in this way:

/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  return array(
    'node_taxonomy' => t('Taxonomy terms of the node')
  );
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  if ($delta != 'node_taxonomy') {
    return;
  }

  // Get a node object form the URL (node/123).
  $node = menu_get_object();
  if (!$node) {
    return;
  }

  // Render the 'field_tags' field from the node object using the 'page' display.
  $rendered_field = field_view_field('node', $node, 'field_tags', 'page');
  if ($rendered_field) {
    return array(
      'subject' => t('Tags'),
      'content' => $rendered_field,
    );
  }
}

Or use Panels, which is precisely designed to build composite pages, and allows you to render the different elements of the node in different places.

Other approaches, especially those involving hacking the theming layer are breaking the principle of separation of structure and presentation.


Remove taxes using Rules after coupon is redeemed I'm attempting to create a rule that removes taxes from a line item after a Commerce Coupon is applied. Is there a way to do this?

Yes, there is a core Drupal Commerce Rules action called "Remove taxes applied to a line item" in the Commerce Tax group. Additionally, via Rules you can inspect field values on any entity to see if they are empty or not. The coupons applied to an order are tracked through a variable called commerce_coupons.

Putting it all together, this means you need to create a custom product pricing rule that looks to see if the commerce_coupons field is non-empty. If so, it should use the action mentioned above to remove taxes. Make sure the weight of your custom rule is set such that it is calculated after the discount that gets added via the coupon.

Note: this cannot be achieved through the Commerce Discount module's interface. It must be done via Rules at Administration > Store > Configuration > Product pricing rules.


How can I print Views language-specific $field variable values inside a views template? I am using Views with "Format Show:Content" instead of "... fields."

I have a multilingual website. In the filters section of Views I have Content: language = user's default language. However, Views refuses to honor this filter selection.

I am also using views-view-fields.tpl.php file to output the fields. currently it is calling, for example, $fields->content to output content.

How can I get Views in Show Content format to honor the language filter? I am familiar with needing to add the 'und' key to certain fields at times, but do I need to do that here? Should adding the filter in the view not be enough? If I do need to add the key where does it go?

If you want, you can see the error in the slideshow at http://goniseko.com

Use dpm() to output $field in your template.

To make PHP not die with an out of memory error, use a static flag to ensure it only prints once.

static $_foo;
if (!$_foo) {
  dpm($field);
  $_foo = TRUE;
}


I see all aliases besides the home page alias (At URL bar) Why is that? I mean, why when I click the home page link at main menu, it is only the site's URL (www.example.com), and not the exact URL of the home page (www.example.com/Decorations-for-all-houses) that appears? how can I make the full URL appear at the home page?

It should be noted that this is the only page with this problem; in all other pages, the FULL URL is always displayed.

If you set your site home page "Decorations-for-all-houses" (or perhaps lowercase would be less confusing) at admin/config/system/site-information, any home link provided by core, contrib modules, themes etc. will point to the right page.

You can edit any link of your main-menu including the home link at admin/structure/menu/manage/main-menu. The default link for home is <front>
which will point to your assigned home page, but it can be any path, including "decorations-for-all-houses".

Themes typically implement their logo link so that it points to the home page without the path, so you would have to edit the theme.

The above (hopefully) covers any case where users already on your site click a home link or logo. But what about visitors clicking a link outside of your site, like Google, or typing the domain name? For redirecting them from www.example.com to www.example.com/decorations-for-all-houses something like the Global redirect module probably would be able to do that.

What people usually seem to want, is just the opposite, redirect from the long url to the root. It might be confusing to visitors if they never can't get to the www.example.com even if they want to. This is what visitors expect to see as the home page url.


Javascript assumed conflict with Drupal I have a website, where I have been trying to build a form with server side and client side validitations of the input fields. More or less I have been achieving progress. Then I put my code from my testing enviroment to the drupal based website, to see how many tweaks do I need to make. Needless to stay lot of things fell apart. Most important at the moment is that my javascript checks if the input field has the correct information, if it does, it colors the input field and changes the helper thex accordingly. This got fully broken on the site. I read a lot and I assumed this may be cause drupal uses an older JQuery that which I was testing with. So with a little help in another question here I invoked the noConcflict and I used the newer jquery with my code. Sadly this did not fix my problem.

The html of the site is located here:
http://www.htconsulting.hu/test/form
The javascript:
http://www.htconsulting.hu/form/validation.js

Ps.: After the noconflict, my popup Jquery UI broke as well, so I hope to find a possible solution outside using noConflict, or solving the popup window now...

You should use the jQuery provided by Drupal and try to work with what Drupal provides (JavaScript, Form API, Theme system, etc.) instead of trying to work without it or, worse, against it. The jQuery update module allow you to use updated jQuery releases in Drupal. That would be 1.6.2 for Drupal 7 and 1.3.2 for Drupal 6. Drupal 7 also provides jQuery UI while for Drupal 6, the jQuery UI module should be used to provide it. This way you can avoid compatibility issues between different version of the same library, unnecessary workarounds and fixes over fixes.

Also, you shouldn't use $(document).ready() in Drupal, but add your function to Drupal.behaviors as explained in the Drupal JavaScript API guide (also available for Drupal 6). And off course, for the form generation, validation and submission server-side code, you should use the Form API.

Keep in mind that your are trying to add a form to a Drupal site, not to a stand alone simple PHP script that doesn't already provides all the (server-side) API your need.


Drupal reference performance I have a project have a lot of field need to be reference by each other.

Does anyone could give me some suggestion about this situation?

How was the performance of field reference? Should I just saving field by text rather than reference type?  (And then render by my custom module code)

There is no performance issue I see with reference field. Reference field holds lot of other things

A table which keeps relationship between two entities which is exposed to other modules where references are saved as entity ids with no control of user input, whereas for text field you do not have much control unless you put validations and turn into almost what reference field is already doing.
Different contributed module are built around reference fields.
As an example you can expose reference fields as relationship to views module.
Text Field is definitely not a replacement for Reference field.
You would not like to get the performance boost for a reference field on the cost of its functionality.
If you have long list of entities to reference, keep the widget as autocomplete that can help in performance boost a bit.


Custom service returns "401 (Unauthorized : Missing required argument merchant_id)" I'm trying to call a custom service module, but it shows 401.

resource:

$resources =  array(
    'get_contacts' => array(
      'operations' => array(
        'index' => array(
          'help' => 'Get customers and their contacts',
          'file' => array('type' => 'inc', 'module' => 'sync_contacts', 'name' => 'resources/sync_contacts.resource'),
          'callback' => '_get_customer_contacts',
          'args' => array(
            array(
              'name' => 'merchant_id',
              'type' => 'int',
              'description' => t('Get customers and their contacts by merchant_id.'),
              'source' => array('data' => 'merchant_id'),
              'optional' => FALSE,
            ),
          ),
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'drupalgap',
            'name' => 'drupalgap.resource',
          ),
          'access callback' => '_sync_contacts_access',
          'access arguments' => array('view'),
          'access arguments append' => TRUE,
        ),
      ),
    ),
  );

Service function:

function sync_contacts_get_customers_list(options) {
  try {
    options.method = 'GET';
    options.path = 'get_contacts.json';//'.json' removed and tested also
    options.service = 'sync_contacts';
    options.resource = 'get_contacts';

    Drupal.services.call(options);
  }
  catch (error) {
    console.log( error);
  }
}

Service function call:

try {
    var my_args = {
        merchant_id: 1
    };
    sync_contacts_get_customers_list({
      data: JSON.stringify(my_args),
      success: function(result) {
        drupalgap_alert("SUCCESSSS");
        $("#contactList").append(JSON.stringify(result, null, 2));
      }
    });
  } catch (error) { console.log(error); }

POSTMAN:

This is how I used the custom service. when I execute it, it shows "401 (Unauthorized : Missing required argument merchant_id)".

How can I fix this issue?

SOLUTION: Used Tyler's resource in his answer below and service call modified as below(changed GET to POST and path modified accordingly).

Note: To test, in POSTMAN also we have to call with POST and pass the merchant_id as Raw ie. {"merchant_id": 1}

function sync_contacts_get_customers_list(options) {
   try {
     options.method = 'POST';
     options.path = 'sync_contacts_resources/get_contacts';
     options.service = 'sync_contacts';
     options.resource = 'get_contacts';

     Drupal.services.call(options);
  }
  catch (error) {
    console.log( error);
  }
}

You have to use the POST method in the sync_contacts_get_customers_list function:

options.method = 'POST';

Without this, you aren't "posting" anything up to Drupal Services, so your resource in Drupal will not be delivered the merchant_id.

If you want to use a GET request, then I'd recommend using a Views JSON (from Views datasource) and a contextual filter(s), otherwise custom resources in Services always use POST AFAIK, unless you're building a CRUD interface for an Entity (e.g. Services Entity API).

Also the way you are defining your custom resource in Drupal is incorrect, use actions instead:

  $resources = array(
    'sync_contacts_resources' => array(
      'actions' => array(
        'get_contacts' => array(
          'help' => 'Get customers and their contacts',
          'file' => array('type' => 'inc', 'module' => 'sync_contacts', 'name' => 'resources/sync_contacts.resource'),
          'callback' => '_get_customer_contacts',
          'args' => array(
            array(
              'name' => 'merchant_id',
              'type' => 'int',
              'description' => t('Get customers and their contacts by merchant_id.'),
              'source' => array('data' => 'merchant_id'),
              'optional' => FALSE,
            ),
          ),
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'drupalgap',
            'name' => 'drupalgap.resource',
          ),
          'access callback' => '_sync_contacts_access',
          'access arguments' => array('view'),
          'access arguments append' => TRUE,
        ),
      ),
    ),
  );


How to replace nodes in quicktab? How can I replace nodes in quicktabs on click of a link?

i guess your using the quicktabs block. if so you can configure here admin/structure/blocks


How to access label of List (text) via node_load() In my module I'm generating some json based on some node content.

$node = node_load($nid);

One of the fields in the node is field_sport_type which is of type List (text). The allowed values look like this:

mens-surfing|Men's Surfing
womens-surfing|Women's Surfing
junior-mens-surfing|Junior Men's Surfing
junior-womens-surfing|Junior Women's Surfing
skate|Skate

When I var_dump($node), the field_sport_type section looks like this:

["field_sport_type"]=>
      array(1) {
        ["und"]=>
        array(1) {
          [0]=>
          array(1) {
            ["value"]=>
            string(14) "womens-surfing"
          }
        }
      }

So, the 'value' is the key from the allowed values, but I want to get the Label, not the key. In other words, I won't want womens-surfing, I want to get Women's Surfing.

How can I get access to the label of my List (text)?

You can get the list of values as a keyed array using list_allowed_values, and use it to show the "key" with whatever logic you want.

An example from the API comments section is as follows:

<?php
/*
assuming there's a field named machine name is 'field_my_field_name' whose
type is a list (float, integer or text), and you want to get the values that
were entered into the "Allowed values list" textarea on the edit screen for the field
*/
$all_fields_on_my_website = field_info_fields();
$allowed_values =       list_allowed_values($all_fields_on_my_website["field_my_field_name"]);
/*
$allowed_values is now an array of $key=>value pairs that
can be dropped into the '#options' value for a form field array, for instance
*/
//example:
$form = array();
$form['my_form_element'] = array(
  '#type' => 'select',
  '#title' => t('Choose something, sucka!'),
  '#description' => t('Descriptive text under form elements rather than above them is a great UX choice, really.'),
  '#options' => $allowed_values,
);
return $form;

Being a "field" in drupal the List field instance attached to a bundle has configuration and settings such as the custom list of items, the default value, whether its mandatory, etc.


Passing Arguments to block in 7.x Views I've got a block view set up to get the latest 3 blog posts by term. I'm providing the default argument with the following:

$path = drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
if($path[0] == 'laws' || $path[0] == 'issues' || $path[0] == 'culprits' || $path[0] == 'themes' :
return $path[1];
endif;

Using dpm on $path[1] gives me the term alias and I assumed that the Argument validator for Taxonomy Terms, which is set to "Term Name converted to Term ID", would get me the ID, but maybe not?

Works fine in views preview with arguments entered, but on an actual page it returns nothing. Never had a problem with this before in 6.x. Is there something new I'm completely missing? I've read through docs and tried a few different ways to return the default arg, but no luck.

Any help would be appreciated.

Thanks

Edited to fix code

Added return ''; to the argument code if the if statement was false. Somehow that did the trick.


How to get field values in rules condition from fetched entity I have a content type "Event" that's linked to a registration type.

Inside rules I want to trigger the action only if a field value from the host entity is "Open" (it's a checkbox field).

Under actions I'm able to fetch the host entity and access this field but i'm baffled how to access the same field under conditions. How can I go about this?

Thanks.

You have to first add conditions that allow the rule to know what fields are available.

To do this you can use combinations of the following conditions:

Entity exists by property
Entity has field
Entity is new
Entity is of bundle
Entity is of type

Those conditions help rules identify the entity and bundle so it can show the relevant fields.

You can then access those field tokens in subsequent conditions and actions.

For example, you might use Entity is of bundle "Event" to then get access to fields used on the event content type.

In your case where you only have access to he user/profile entity you would have to add a condition like above to determine the entity/bundle of the user/profile so that you could get access to the field that references the event.

Then have an action to load the event entity (you could use the action "Fetch entity by id") using the entity id in that field.

Then you could add an if condition in the actions (using the conditional rules module) and say if the fetched entity is of type "Event" then if the value of your field is "Open" then do your final action.

It's a bit complex but you should be able to achieve what you want using the conditional rules module.
I think though that this will only work if you have a field on the user that references the event.

If it is the other way around and you have a field on the event that references the user then it would work differently.

In that case I would use the "Fetch entity by property" action to fetch content where the checkbox field = "Open".


PDOStatement::execute takes 11s, what to do? Our Drupal site is sslllooooowwwww, at best taking 3s for static-content pages, at worst 11s for shopping cart pages. Above is the profile for visiting the shopping cart. Profiling reveals that PDOStatement::execute is the #1 time consumer. Any advice why or what to do about it?

Not sure if indicator that my connection has problems, Drupal is inefficiently sending data, or if it's time to learn how to tweak MySql.

It could mean any of a bunch of things.  PDOStatement::execute() is just the final method that gets called for each and every database query Drupal makes (which can be quite a few).

First, make sure you Apache is configured properly, and that APC is installed and has enough memory.

Then, I would make sure your MySQL instance has a decent starting point.  Download, run, and follow the advice of mysqltuner.

Then, download/install/enable the Performance Logging and Monitoring module and play around with the reports.

Figure out what is slow, and fix it.

There are also bunches of posts with other profiling advice, too, as well as advice for performance improvements beyond basic configuration (eg, advanced caching strategies).


Formatting Field Collection data with Views Data Export (CSV) I've got a Field Collection on use in a basic page content type on my Drupal 7 site. I've built a view with the Data Export module that is outputting the data from nodes of this content type as a CSV. The view is configured to dump all of the Field Collection data for each parent node into one cell... not ideal, but I'll live with it.

The problem is that there is no separator between the fields in the Field Collection. So, the contents of the Field Collection cell in the CSV looks like this:

Fruit_1: AppleFruit_2: OrangeFruit_3: Banana

It makes reading through the data in that cell unbearable (the separator should be after Apple and Orange... oh and fruit is just for this example, not actual data).

How do I get some kind of separator in there? Doesn't have to be anything fancy; something as simple as a comma and a space would be lovely! Ex:

Fruit_1: Apple, Fruit_2: Orange, Fruit_3: Banana

I've experimented with Field Collection Views, but no luck.

The solution is to implement a views_pre_render hook in a custom module.

function mymodule_views_pre_render(&$view) {
    if ($view->name == 'myview') {
        foreach ($view->result as $key => $row) {
            $line = array();
            foreach ($view->result[$key]->field_field_fruit_collection as $n => $collection) {
                $item = current($collection['rendered']['entity']['field_collection_item']);
                $line[] = $item['field_fruit'][0]['#markup'] .  ' (' . $item['field_color'][0]['#markup'] . ')';
                unset($view->result[$key]->field_field_fruit_collection[$n]);
            }
            $view->result[$key]->field_field_fruit_collection[0]['rendered']['#markup'] = implode(', ', $line);
        }
    }
}

In this example, the collection field is field_fruit_collection which is made up of two fields: field_fruit and field_color. The contents of the exported collection field will look like :

"Apple (red), Banana (yellow), Kiwi (green)"


Where and how does drupal store the node body in drupal 7? I am programatically trying to create a custom node to store some content, which I would like to display on a page.
Following is how I am executing it.

    $node = new StdClass();
    $node->name = $value;
    $node->title = $node->name;
    $node->language = LANGUAGE_NONE;
    $node->body[$node->language][0]['value']   = $javascript.$html;
    $node->body[$node->language][0]['summary'] = $type;
    $node->type = "custom_type";
    $node->created = time();
    node_save($node);

I notice that the content I inserted are present in the tables
'field_data_body' and 'field_revision_body'
I try to load the node and get the content

   $query = new EntityFieldQuery();
   $entities = $query->entityCondition('entity_type', 'node')
              ->propertyCondition('type', 'custom_type')
              ->propertyCondition('title', $type)
              ->execute();
   if (!empty($entities['node'])) {
        $node = node_load(array_shift(array_keys($entities['node'])));
        $html = $html.$node->body[$node->language][0]['value'];
   }

But what puzzles me is how from where is the content being loaded. I deleted the entries in both 'field_data_body' and 'field_revision_body', but the content still gets loaded.

So how does drupal7 save and load the contents of the node body?

If you emptied out the field_data_body (and revision) table and you are still getting data that can only mean three things:

you emptied the wrong table (wrong database or the right database with the wrong prefix)
it's still cached (there's a clear cache button on the admin/config/development/performance page).
You are not using SQL to store your fields. Do you have mongodb_field_storage enabled? Something even more exotic?

As for how it gets stored, node_save calls field_attach_insert (and node_load calls field_attach_load) which, in turn, calls the field storage module which I presume is field_sql_storage and so field_sql_storage_field_storage_write writes your database records and field_sql_storage_field_storage_load loads them.

Also note that array_shift(array_keys()) is wrong (E_STRICT error: Only variables should be passed by reference because array_shift takes a reference and array_keys is not returning by reference. Finally, you should feed your EntityFieldQuery code to the coder module to fix the coding standards: at least the code inside the if is indented wrong and the string concat operator (the dot) needs spaces on both sides. It hurts my eyes :)


How do I access variables displayed in devel? Using devel I'm able to retrieve the names of certain variables and how to access them.

For example I might want to use the book menu name. Devel has it listed as so

$...->book['menu_name']

But I'm not sure how to print that info in page.tpl.php or access it in general. I'm also not sure what to replace the $... with.

I've tried the following with no luck.

print $page->book['menu_name'];
print $node->book['menu_name'];
print render($page->book['menu_name']);
print render($node->book['menu_name']);

If you want to do any theming to node use node.tpl.php instead of page.tpl.php

in page it is not suggested. If you want to render a field in node.tpl just write the following

<?php print render($content['menu_name'])?>

or simply

<?php print $node->book['menu_name']; ?>


Multiple files with different language I want to make a field with type file and this field with multiple values, so far I know that its simply possible but I want also to some thing like bundle field with each file uploaded and this field is representing language.

Example: Suppose I upload 3 files in same field for the same node & each file with different language (file_1 => English , file_2 => French , file_3 => German) and so on.

So is there any module can accomplish that, or its something I should do custom?

I want a solution like the attached image

Are you looking for field_collection?

Install and enable the module.
Add a field of type "Field Collection" to your entity type.
Go to admin->structure->Field COllection
Add 2 fields
1 field is of file type
2 field is either select box with countries or can be taxonomy reference field

Now while creating the content, you will have option to upload a file and select a language for it.


How to use ip to visit AcquiaDevDesktop's site? I want to visit drupal site through 'Local area network'.

For example, my server ip address is 192.168.0.1, My drupal site is http://daxuebao.local:8083/

I try to use 192.168.0.1:8083/daxuebao.local, 192.168.0.1:8083/daxuebao. But can not be visited.

Ok, i get it. I installed Acquia Dev Desktop and tried it out. This is what I think is what has happened and what the problem is:

You installed Acquia Dev Desktop and entered parameters about the default site that comes with Acquia (this is required during installation - so this must have happened). This site is what you reach when you from another computer enter 192.168.0.1

You created the daxuebao site via Acquia Dev Desktop application and entered "Sitename" as daxueabao and you did not enter a "URL Path" so the result is that "Site Path" then becomes "daxuebao.localhost:8083". This means that the Apache software in Acquia Dev Desktop will examine every request it receives and determine if it should go to (a) the default site or (b) the daxuebao site.

The problem is that the daxuebao site is local and that your client computers on the LAN does not know where "daxuebao.localhost:8083" points... the have no knowledge of what IP number that corresponds to and if you enter just 192.168.0.1 the Apache software will determine that to be a request for the default site. The only site that is not local is the default site.

There are basically 3 different ways of solving this problem (which one depends on your need):

Solution 1: add a DNS record to the local DNS if you have one (I don't think you do) or

Solution 2:  add a DNS record to the hosts file of all of your client computers (see more at www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/ ) or

Solution 3: move site duxuebao to the default site so that Apache servers that codebase and data instead. Make sure you backup files and database before you do it. I can tell you exactly how to do it if you tell me what operating system you are using.

Added in response to comments:
I would do it like this:

Oh, by the way. Acquia Dev Desktop works out of the box on port 8082 and not 8083, just to be sure here, you're not working with multiple installations of Acquia Dev Desktop? If not then:

1 Backup the daxuebao site:

1.1 Open the Acquia Dev Desktop control panel

1.2 Click the Settings button

1.3 Click the Sites tab

1.4 Highlight the daxuebao site

1.5 Click Export button, select "to file"-option to download a copy to your Desktop.

1.6 Backup done (files and data)

2 Backup the default site:

Note: Do this just to be sure.

2.1 Open the Acquia Dev Desktop control panel

2.2 Click the Settings button

2.3 Click the Sites tab

2.4 Highlight the localhost site

2.5 Click Export button, select "to file"-option to download the export to somewhere.

3 Replace the default site FILES with the daxuebao site FILES:

We cannot use the Acquia Dev Desktop import feature here unfortunately because the default site is reserverd/protected. We need to do the copying manually of files (step 3) and data (step 4):

3.1 Stop servers in Acquia Dev Desktop from it's control panel

3.2 Delete all files in /Users/YOUR-COMPUTER-USER-NAME/Sites/acquia-drupal/sites/default

3.3 Copy all files in /Users/YOUR-COMPUTER-USER-NAME/Sites/acquia-drupal/sites/daxuebao.localhost to /Users/YOUR-COMPUTER-USER-NAME/Sites/acquia-drupal/sites/default

3.4 Start servers in Acquia Dev Desktop from it's control panel

3.5 File copy complete.

4 Replace the default site DATA with the daxuebao site DATA:

Both sites default site and daxuebao are now using the same database. That's not good because if you delete the daxuebao site then the data will disappear. So we need to copy the data from database daxuebao to the acquia default database.

4.1 Extract the files downloaded int step 1.5 on the desktop ( it will extract to /Users/YOUR-COMPUTER-USER-NAME/Desktop/daxuebao.localhost ). This folder contains data and files.

4.2 Go to the In the Acquia Dev Desktop controlpanel click button "Manage my database" and a browserwindows with phpMyAdmin will appear.

4.3 Select the database acquia_drupal in left part of the window. In the right part of the window all tables in the database will appear.

4.4 Go to the bottom of the page in the right part of the window and select "check all" and

4.5 delete the tables by using the dropdown to the immediate right labeled "With selected:" and select "Drop".

4.6 Confirm deletion.

4.7 Now, we're going to import the data from the daxuebao site

4.8 Click on the tab "Import" at the top of the right hand window.

4.9 Click button "Choose file".

4.10 Navigate and select the datafile daxuebao.sql thats in the /Users/YOUR-COMPUTER-USER-NAME/Desktop/daxuebao.localhost directory.

4.11 Click button "Go"

4.12 Data copy complete.

5 Change settings-file for default site to look at correct database table

5.1 Open settings.php in /Users/YOUR-COMPUTER-USER-NAME/Sites/acquia-drupal/sites/default directory

5.2 Change
    $base_url = 'http://daxuebao.localhost:8082';
to
    $base_url = 'http://localhost:8082';

5.3 Change
    $db_url = 'mysqli://drupaluser@127.0.0.1:33066/daxuebao';
to
    $db_url = 'mysqli://drupaluser@127.0.0.1:33066/acquia_drupal';

5.4 Change
'database' => 'daxuebao',
to
'database' => 'acquia_drupal',

5.5 Verify by going to the site from your local computer

5.6 Verify by going to 192.168.0.1:8083 from another computer within the LAN

5.7 If all looks fine then your default site in Acquia Dev Desktop is now using it's own database "acquia_drupal". You can now safeley delete the daxuebao site from your Acquia Dev Desktop controlpanel.

BR / Fredrik


How do you configure it so a published article promoted to another page instead of "front page"? I have a main menu with:

"Home" -basic page
 "Contact us" -the default drupal contact form
 "news" - which I want all the news articles to dynamically publish to the top so that when people click on news they see the latest article.

I thought that making a menu item in the form of an "article page" might do it but that only seemed to be comfortable with a single article. I made it into a book and it has allowed me to create a page but the formatting has gone dead weird so I would like to be able to create my articles and click an option which allows me to promote my articles to the news page. Is this possible?

Thanks

With Views, you can use "promoted to front page" as a filter value, so that things with that box checked can also be "promoted" to any page view that takes that as a filter.

If you don't want to us the native "promoted to front page" checkbox, but would rather have a separate checkbox just for that page, you can add a custom field to your content type(s) and use that as a filter value instead.


Get the real path of a file I am creating an Excel reading module in Drupal 8. I want to get the real path of a file for reading it from a path like public://2016-03/Places.xls.

What function should I call for getting the real path of a file?

Finally I got the solution by digging Drupal code.
We can get the real path or absolute path by using the file_system service.

$absolute_path = \Drupal::service('file_system')->realpath('public://2016-03/Places_2.xlsx');


Difference between theme preprocessor & processor function? The question is is self-explanatory!

Another question, suppose I have a template file named a-b--c--d.tpl.php

What would be the preprocessor function for this template file? I suppose themename_preprocess_a_b__c__d(&$vars)?

Sorry for my poor knowledge. I'm newbie to drupal & started with drupal 7.

For the template

If the page is "/my-node", the page template will be "page--my-node.tpl.php".

For the Prepocess

But you cannot using it "themename_preprocess_my_node(&$vars)" because my-node isn't a hook ! You can find differents hooks with this page http://api.drupal.org/api/drupal and with the search box,  type 'theme_'. You can see the differents hooks for the preprocess


Which is the highest version of Solr that is compatible with the "Apache Solr Search" module? I have a setup of Drupal 7 with the Apache Solr Search module. I am planning to upgrade the solr server's current installed version(3.6) to a higher version.

The latest version of Solr available in their site is 8.5.1.

Which is the highest version of Solr that is compatible with the module?

Given there is an issue in the project issue queue (Solr 7 integration) about allowing to use the module with Solr 7, the module is at the moment only compatible with Solr 5 and eventually Solr 6.

Notice that the README.txt file has not been updated since 6 years ago and that the solr-conf directory contains configuration files for Solr 1.4, 3.x, 4.x, and 5.x. This means the module has been tested with Solr 5.x, at least the 5.x version that was available 4 years ago.


How to create an article sharing site? I need to design a site which would let people write & share their articles, essays, poems, pretty much any written stuff. It should have complete Facebook integration - registration, likes & comments all from Facebook API.

I found that Drupal would be perfect designing such a site.

I've never used Drupal before. Any advise on how to go about making such a site using Drupal? Are there any contributed modules I could use?

Because you are very inexperienced with Drupal, you don't know that your question is actually a set of several questions.

If you never have used Drupal before, you must understand a few basic things about Drupal, then learn about how to install it, and how to administrate (and customize) your Drupal to add the features that you want.

Also, Drupal has installation profiles; there are a variety of "pre-configured" versions of Drupal you can download and use for common needs. I am not sure any profile exists that is specialized for your needs, but you can search and select the most suitable and customize according your needs.

Update:
If you have installed a Drupal version, and have reviewed the basics of Drupal administration, you can find and test several options for modules to (integrate with Facebook](http://drupal.org/search/apachesolr_multisitesearch/facebook%20Integration?filters=ss_meta_type%3Amodule). For letting people share their content, you can review that with Content Types and CCK fields (CCK is needed for Drupal 6) you can create separated types of content having custom fields according your needs.

here http://drupal.org/documentation/modules/field-ui and here http://drupal.org/node/774728 are documentation about how to create a Content Type, and here is screenshot about where you can add custom fields for Content Types:

Remember review Drupal profiles, can be a suitable answer that you can customize with content types and Facebook integration.


Any way to do custom action from clicking an #autocomplete_path option I'm attempting to hack the search_autocomplete module. I inject my own suggestions in the matches portion in order to grab results from external sources. I would like to make it so that when I click one of these external suggestions, instead of filling in the search box, it re-directs the user to this external source. Is it possible to do this?

It is not possible: The purpose of the autocomplete callback is to offer suggestions to autocomplete what the user is entering.
Basing on what entered from the user, the callback needs to return the possible values the user could be writing; it is not supposed to redirect the user to a different page, considering that the user has not selected any of the values returned from the autocomplete callback, and that the callback doesn't know which of the returned values the user selected.


$views->render() does not display node_path So I made a view and Im trying to pull the results into an array (which I am json encoding and sending to javascript but thats neither here nor there) but some of the node information isnt being pulled. Specifically the node_path.

When I preview the view in the edit views page in the backend, the path shows up. But when I pull the view on the front end from my preprocess_page function the node path is not outputted.

In my view, I'm displaying the following fields:

Node: Post Date
Node: Title
Node: Teaser
Node: Type
Node: Path

And each of these fields shows up in the preview. But when I try to pull the view using the code below the path isnt output:

$blog_posts = json_encode(theme_get_view_result('front_page_blog_blocks'));

function theme_get_view_result($viewname) {
  // views_get_views_result($viewname) produces the same result as $view->result;
  // Im just showing that I tried both
 //return views_get_view_result($viewname);

  $view = views_get_view($viewname);
  if(!empty($view)){
    $view->preview();
    return $view->result;
  }else{
    return 'empty';
  }
}

what I also noticed, is that the date was output as a unix timestamp, and not the format I selected (custom, 'M j').

So the result produced in my console is:

    {"nid":"1","node_created":"1312470739","node_title":"blah blah blah this is my title","node_revisions_teaser":
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor vestibulum gravida. Proin ornare nisi non orci feugiat ut hendrerit mi venenatis. Etiam diam ligula, pellentesque et vehicula sed, ultrices at lorem. Vivamus consectetur risus nisl. Vivamus luctus volutpat dolor,","node_revisions_format":"2","node_type":"blog"},

So notice: there is in incorrect timestamp, and the node path is missing. Im a total Drupal noob so I have no idea whats going on.

aha! turns out render() only produces data saved in the database, and node paths are not saved in the DB. So my solution was to grab the node id from the rendered view, use that to get the node paths, and created a new field with that path like so:

function theme_get_view_result($viewname) {
  // views_get_views_result($viewname) produces the same result as $view->result;
  // Im just showing that I tried both
 //return views_get_view_result($viewname);

  $view = views_get_view($viewname);
  if(!empty($view)){
    $view->preview();
    return $view->result;
  }else{
    return 'empty';
  }
}

$blocks = theme_get_view_result('front_page_blog_blocks');
foreach($blocks as $k=>$v)
{
  $node_path = drupal_lookup_path('alias','node/'.$blocks[$k]->nid);
  $blocks[$k]->node_path=$node_path;
}


How do I create a view that uses data from an external site I have a site that needs to get articles data from a view in site A in order to display these articles as a view in site B.

I found the module Services Views, which i don't completely understand.
I have installed it in site A, and created a services resource of a view with services display.

But how do I create a view in site B that displays the articles using that services endpoint?

You can use views_database_connector and include connection details to your settings.php and database will be available to views

add connection details to your settings.php

"example_db" = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'example',
      'username' => 'example_user',
      'password' => 'example_pass',
      'host' => 'xxx.xxx.xxx.xxx',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

and when you create a view you can choose specific table from this database to connect to

Should work for both drupal 7 & 8


custom service respond me : 401 Unauthorized: Missing required argument foo I have this custom service:

function zbs_services_resources() {
  return array(
    'productQuestionForm' => array(
      'actions' => array(
        'send' => array(
          'help' => 'save a FOO entity via send form',
          'file' => array('file' => 'inc', 'module' => 'zbs'),
          'callback' => '_zbs_productQuestionForm_create',
          //'access arguments' => array('note resource create'),
          //'access arguments append' => FALSE,
          'args' => array(
              array(
                'name' => 'foo',
                'type' => 'struct',
                'description' => 'The FOO to create',
                'source' => 'data',
                'optional' => false,
              ),
            ),
        ),
      )
    )

  );
}

And this little jQuery code in a simple html test file:

$.ajax({
    url: "/rest1/productQuestionForm/send",
    headers: { 'Content-Type': 'application/json','X-CSRF-Token':'MY_WORKING_TOKEN' },
    success: function (res) {
      alert("success");
      console.log(res);
    },
    data : {
      'foo' : 'pippo',
      "type":"page",
      "title":"Page submitted via entity JSON REST",
      "body": {
          "value": "
test
\n",
          "format": "filtered_html"
      }
    },
    type: 'post',
    dataType: 'json',
  });

But when I load the simple test html page I see this in developer suite for the POST url:

  401 Unauthorized: Missing required argument foo

Where am I doing wrong?

The problem is the mismatch between the data type you define for foo ('struct'), and what you pass with JavaScript (a string). If you are going to pass a string, then your hook implementation should be the following one.

function zbs_services_resources() {
  return array(
    'productQuestionForm' => array(
      'actions' => array(
        'send' => array(
          'help' => 'save a FOO entity via send form',
          'file' => array('file' => 'inc', 'module' => 'zbs'),
          'callback' => '_zbs_productQuestionForm_create',
          //'access arguments' => array('note resource create'),
          //'access arguments append' => FALSE,
          'args' => array(
              array(
                'name' => 'foo',
                'type' => 'string',
                'description' => 'The FOO to create',
                'source' => 'data',
                'optional' => false,
              ),
            ),
        ),
      )
    )
  );
}

'source' => 'data' is perfectly fine, as shown in the example at hook_services_resources(), but notice what the documentation says.

  In the case of 'data' unless you put things in an array, you will get passed to your functions. 'source' => array('data' => 'nid') will pass them off as a single variable; 'source' => array('data') will give you all argument values to each argument.


How to grow block menu on hover I am trying to make secondary menu grow on mouse hover. just like this site

we can see on the bottom of the page. menu block can grow bigger and show more menu.

any idea what technique used to make something like that. or maybe a module or maybe jQuery. right now i'm still googling but still got no clues.
Please let me know some idea about this.

Regards

mbahlol
pardon for my english

Here is a jsfiddle that will show 3 different techniques. http://jsfiddle.net/3rYCs/


How do I switch node templates based on arbitrary critera I'm trying to switch the node template file based on a variable, in drupal 6 you could simply set  $vars['template_file'] = 'node-whatever'; from with the preprocess_node() and name the new node template file node-whatever.tpl.php.
I drupal 7 this is gone. I looked through the docs and it appears that in Drupal 7  its   $vars['theme_hook_suggestion'][] = 'node--whatever'; but this is not working for me. Am I doing something wrong? is there a naming convention that I'm missing? The documentation is a little confusing

Indeed, in D7 the template suggestions are an array of suggestions, in the order of importance. You've got 99% of it, but your dashes need to be underscores. Try:

function THEME_preprocess_page() {
  $vars['theme_hook_suggestions'][] = 'page__whatever';
}

function THEME_preprocess_node() {
  $vars['theme_hook_suggestions'][] = 'node__whatever';
}

Why underscores instead of hyphens? From the Drupal API docs:

  // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  // Theme suggestions should only contain underscores, because within
  // drupal_find_theme_templates(), underscores are converted to hyphens to
  // match template file names, and then converted back to underscores to match
  // pre-processing and other function names. So if your theme suggestion
  // contains a hyphen, it will end up as an underscore after this conversion,
  // and your function names won't be recognized.


Why are hook_form_alter updates being reverted? After I clear all caches I can see my update is effective in the Create Article form. Great.

But as soon as I refresh the page, or come to it afresh to create another Article, the unmodified value of #file_upload_title re-appears.

This is what I added to template.php:

function seven_form_article_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_photo_gallery']['und']['#file_upload_title'] = 'Add a new file or multiiple files';
}

The function seven_form_article_node_form_alterwas correctly named but not placed in the correct file in the correct folder.

The function seven_form_article_node_form_alter has to go in template.php in a (sub)theme of the administration theme seven - of course - and not in the  template.php of my "front-end" theme.

The fact that I had a function in there with a prefix other than my from-end theme's should have signalled my mistake.

What mislead me was a quirk of Drupal cache clear. It happens that  clearing the Drupal cache actually (and incorrectly) caused my form alterations to be displayed as my function must have been the last one in the chain to have taken effect. It was only after a subsequent page build / refresh that the form alter's effects (correctly) disappeared.  So this is a quirk of Drupal cache clear that needs to be taken account of in this edge case.

Consequently I have created an administration sub theme into whose template.php file the function now sits (Does it count as one line of code or two? ;-). All is now working as it should.


Use tokens in PHP filter i want make a photo gallery with drupal and i need to:

a download button for current node picture
an embed code that allow visitor to use photo on other Websites. like this:

i have some experience with Drupal and reading PHP codes, but no experience with writing PHP codes. i tried to make a block in bottom of node picture with PHP filter and following content:

<a href="<?php t('[node:url]'); ?>" title="<?php t('[node:title]'); ?>"><img src="<?php t('[node:field_image]'); ?>">

this code not work. please help me.

many thanks :)

To translate the tokens in their values, you can use:

token_replace

e.g:

$nid = token_replace('[node:nid]', array('node' => $node));

You need to be able to pass the required parameters for that token, e.g $node for node tokens.


Error while creting field help needed I am trying to create a field  in hook_install() using the
following code.

$field = array(
  'field_name' => 'unit_count',
  'type' => 'text',
  'cardinality' => FIELD_CARDINALITY_UNLIMITED,
);

field_create_field($field);

$instances = array();

$instances['unit_count'] = array(
  'field_name' => 'unit_count',
  'label' => $t('unit_count'),
  'description' => $t('unit_count'),
  'widget' => array(
    'type' => 'text_textfield',
  ),
  'required' => TRUE,
  'settings' => array(
    'text_processing' => 0,
  ),
);

foreach ($instances as $instance) {
  $instance['entity_type'] = 'node';
  $instance['bundle'] = 'first_example_bundle';
  field_create_instance($instance);
}

I am getting the following error:

  Notice: Undefined index: id in field_create_field() (line 173 of /Library/WebServer/Sites/Dev/Public/Peirce/modules/field/field.crud.inc).

What is wrong with the code I am using?

Im not sure what your error is. Every field has different widget settings and differing options ... keeping all the options you can set straight in my head is beyond me ... I have created fields in install profiles and using hook_install.  I tend to build the fields using the Field UI found at Structure -> Content Type -> then add/edit Fields then export those settings to code for use in a module.

I found this blog post immensely helpful:

Exporting and creating field definitions in Drupal 7

From the blog post you can get a field and its instance config with:

$field_data = field_info_field('field_article_image');
$instance_data = field_info_instance('node', 'field_article_image', 'article');

You can create a field and instance(s) in PHP using the Field API:

field_create_field($field_data);
field_create_instance($instance_data);

You can use Devel or Drush with drush php-script or eval and the following code nabbed from the blog post. It will generate the above 2 lines of code with the $config and $instance data all filled out for you to use in your custom code:

$entity_type = '';
$field_name = 'field_';
$bundle_name = '';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

EDIT:

Once you see a valid export from an example field you are trying to create. It can be easy to re-use, tweak, or fix small parts of that field configuration to use in the same project or other projects. But I never sit down from scratch and try to code it all by hand for every field.


how to convert Taxonomy terms to nodes Short Question :

is there a way convert all of one vocabulary taxonomy terms to one
content type nodes ? And switch all term refrences in the database to
entity references to the converted term/nodes?

Details :

A long time ago, I have made a website for music and i used the core
terms for local singers and performers now i want to use entity
reference for a better content control user interface.

the website has one content type "Audio File" The content type
fields are :

Audio file : file upload
Performer : term reference of vocab "Performers"

The taxonomy term fields are -Vocab : "Performers:

Performer Name : title field.
Performer Portrait : Image upload field

the site is running and there is already more than 150 singers and over 1000 audio files. So doing this manually is almost impossible.
I think i should use migrate module but i don't know how to use it and it seems very complicated !

Thanks :)

Export taxonomy using https://drupal.org/project/taxonomy_csv

Then use excelent https://drupal.org/project/feeds module and create node importer and map fields accoridingly.


How to add a text Autocomplete Widget programmatically Trying to include a text Autocomplete Widget in a compound field (more here) using the snipped below.. but the field does not autocomplete. What am I doing wrong?

  $element['contact_name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => $defaults['contact_name'],
    '#weight' => 2,
    '#size' => '100',
    '#max_length' => '255',
    '#widget_type' => 'autocomplete_widgets_flddata',
    '#autocomplete_match' => 'contains',
    '#autocomplete_case' => '0',
    '#widget_module' => 'autocomplete_widgets',
  );

Ok, so if you're trying to do it through hook_form_alter, you have to read the documentation on altering CCK fields.

The short version: the CCK fields are processed after the form is built. If you want to change anything in them, you have to add a callback to $form['#after_build'] (but do not replace the array, just add to it). Then implement the function, change values in $form and return the $form.


How to list custom navigation menu with submenu? I have created a custom menu in a drop-down manner. How can I show this custom menu with it's subitems programatically, so that I could customise it's styling?

You can use below function to render your custom menu your way

function _custom_menu_overview_tree_form($tree) {
  $output = '';
  foreach ($tree as $data) {
    $item = $data['link'];
    if ($item && $item['hidden'] == 0) {
      if(strtolower($item['title']) == 'about us page condition'){
            $output .= '
';
      }else{
            $output .= '
';
      }
      (0 == $item['plid']) ? ($class = 'parent') : ($class = 'child');

      if(isset($item['options']['attributes'])) {
        $attributes = array('attributes' => array_merge($item['options']['attributes'], array('class' => array($class))));
      } else {
        $attributes = array('attributes' => array('class' => array($class)));
      }

      $output .= l($item['title'], $item['href'], $attributes);

      if ($data['below']) {
        $output .= '
' . _custom_menu_overview_tree_form($data['below']) . '
';
      }
      $output .= '
';
    }
  }
  return $output;
}

And use below code in your html.tpl.php or where you want to render your menu

$menu_items = menu_tree_all_data('your menu name');
echo '
' . _custom_menu_overview_tree_form($menu_items) . '
';

Please try this and let me know if any issues.


Get values from views exposed filter in hook_views_pre_view I would like to get the current values from an exposed filter in hook_views_pre_view().

For example, if the input filter has some value I would like to change de pager: number of items, the problem is how to get this value from views without using $_GET because I don't think it will work with views ajax.

What is the right way to get current exposed filters values from a view?

I've found it, there is a views method:

$input = $view->get_exposed_input();


Adding a new separate menu link to /admin/config in page? Adding new separate menu link in admin config page  like development service

Adding link to admin config under development, media, service is easy but creating new separate menu like admin_config_development, admin_config_service , admin_config_media is bit tricky.

As mentioned in

  Create same file with small alteration  modulename.links.menu.yml

modulename.admin_config_modulename:
  title: ' settings'
  description: ' selection.'
  route_name: modulename.settings
  parent: 'system.admin_config'
modulename.second_link:
  title: 'settings'
  description: 'selection.'
  route_name: modulename.settinganother
  parent: 'modulename.admin_config_modulename'
  menu_name: modulename

  By: monkpal


Scheduler changes node language on publish The scheduler changes the node's language to default-language while publishing.

This happens if the scheduler is run by drupal's cron (called by system-cron or manually) and scheduler's lightweight cron (called by system-cron), but if i start the scheduler's lightweight cron manually by admin-interface it's published with the correct language settings...

It happens on both, single nodes and on translated nodes.

I tried for hours with different settings and configurations. The problem occurs on 2 big sites (with 3 languages), but not on 1 low-level site (with 2 languages).

Any idea?

Find the difference between your low level site and the big ones. Perhapsyoushouldcompare their node tables once before and once after you have published content onthem. Make shure, that the modules and settings are the same while running these tests.


How to replace usage of static Entity::load method calls for better testability? In my method that I'm testing in UnitTestCase based class I have a statement:

Term::load(self::HARDCODED_TID);

Any other way to load Term object to make it 'mockable'?

My workaround is (without changing legacy code):

   $entityManager = $this->getMockBuilder('\Drupal\Core\Entity\EntityManager')
      ->disableOriginalConstructor()
      ->getMock();

    $entityManager->expects($this->any())
      ->method('getEntityTypeFromClass')
      ->will($this->returnCallback(function ($class_name) {
        return $class_name == 'Drupal\taxonomy\Entity\Term' ? 'taxonomy_term' : '';
      }));

    $term = $this->getMockBuilder('Drupal\taxonomy\Entity\Term')
      ->disableOriginalConstructor()
      ->getMock();

    $termStorage = $this->getMockBuilder('\Drupal\taxonomy\TermStorage')
      ->disableOriginalConstructor()
      ->getMock();

    $termStorage->expects($this->any())
      ->method('load')
      ->willReturn($term);

    $this->termStorage = $termStorage;

    $entityManager->expects($this->any())
      ->method('getStorage')
      ->will($this->returnCallback(function ($type) {
        return $type == 'taxonomy_term' ? $this->termStorage : NULL;
      }));

    $this->container = new ContainerBuilder();
    $this->container->set('entity.manager', $entityManager);
    \Drupal::setContainer($this->container);


Moderate user uploaded images I want offer a solution that a registered user can upload Images through File entity but like Copyright, Privacy and laws i want to check the image before the Image will be public.

The best solution would be if the not checked image would be temporary in a folder. If the Image is ok then i want to select it and change it to other other folder which has public access. (i can play here with CHMOD permissions on Linux). If the image isn't ok it should be deleted and not reachable via public access.

The background is, if a image including copyright infringement or other criminal materials then it should't be public reachable. It means if i hidden or don't make it with Views public in Frontend available a visitor can with right URL open the image.

I use the modules:

File Entity (last dev)
Views 3
Panels 3
VBO Views Bulk operations

Has anyone an idea? Maybe with Rules module?

You should consider using File admin module.

  File admin extends the File entity module to add administrative
  options to files, including published, promoted, and sticky status.

If you decide to use the module please also look at the issue queue. Although the module is stable a few extras can be had by applying a few select patches, especially Create tie in for views_bulk_operations as you are using that module.


Commerce create order when registering a new account I would like to create an order  automatically when a request for a new account is done. So far I have created a rule that triggers on "After saving a new user account". The product, in this case a membership is added to the cart, but I cannot seem how to update the order with the address details of the user ?
I have tried creating a new entity,  Commerce Customer profile, and setting its values but these values are not added to the order? Could it be that the new profile is not "connected" to the order? How should that be done?
Any ideas welcome.

Thanx,

/bo

Perhaps the question is unclear but really I need to know what steps to include in the rules to be able to extract the user details, and add these to the created order, and then invoice the user.


"the website encountered an unexpected error.Please try again later" after db_update Drupal responses "the website encountered an unexpected error.Please try again later" after running db_update statement in my custom module. I always do this without any error. Any suggestion pls!

function mobile_user_form_submit($form, $form_state){
    $deposit=$form_state['values']['deposit'];
    $status =$form_state['values']['status'];

    $id = $form_state['values']['hid'];
    drupal_set_message(t($id ." / ". $deposit." / ".$status));
    if($id != ""){
    db_update('mobile_users')
        ->fields(array('deposit' => $deposit, 'status' => $status, "updated" => date('Y-m-d H:i:s')))
        ->condition('id', $id)
        ->execute();
    drupal_set_message(t('successfully saved.'));
   }
}

After comment db_update() statement, it is ok no error message show.

Thank you,

------ Solved -------

And I try to update manually that record in mysql, in the field "deposit" I got an error message "Please select a value not more than 127". I found myself I set wrong datatype in deposit field, I was willing to set Integer datatype but I was not awared what I had set I set tinyint. After chaning tinyint to integer, "the website encountered an unexpected error.Please try again later" also removed.

Thanks

Once try to insert manually in mobile_users(phpmyadmin) table with same data.
Then check for any errors, if not then check recent logs/apache error logs for more suggestions.


Can't update the second front end I tried to run drush up on two front-ends (sharing a common database server). The first server went right and updated Drupal and modules just fine. But when I tried to run the same command on the second front end I just got:

Command pm-update needs a higher bootstrap level to run - you will   [error]
need to invoke drush from a more functional Drupal environment to run
this command.

Yes, I am on the same directory on both servers. And yes, the SITE works on the second front end (checked with change to hosts) so it surely gets connection to the database server.

If I run drush status the outputs are same EXCEPT FOR missing "Drupal bootstrap: Successful" and lines for Drupal user and two Theme lines missing. So any ideas how to start resolving this problem?

hank

Drush uses the database to determine what versions of modules are installed; therefore, Drush believes the second frontend to be up-to-date, even though the code is still at an older version.

To update your site:

Do not update live. Make a local dev environment by copying one of the frontends and the database.  Update the local dev environment
After updating and testing the local system, push the new code to the live systems.
Run drush updatedb on both frontends


open_basedir restriction in effect despite file directory within web root When trying to upload a logo to my Zen 3.1 subtheme (Appearance > Settings) I get the following error:

Warning: is_file(): open_basedir restriction in effect. File(/tmp/phpillr69) is not within the allowed path(s): (/home/testwww/web/) in image_get_info() (line 126 of /home/testwww/web/informator/includes/image.inc).
Warning: realpath(): open_basedir restriction in effect. File(/tmp/phpillr69) is not within the allowed path(s): (/home/testwww/web/) in drupal_realpath() (line 2177 of /home/testwww/web/informator/includes/file.inc).
Warning: getimagesize(): Filename cannot be empty in image_gd_get_info() (line 349 of /home/testwww/web/informator/modules/system/image.gd.inc).
The specified file logo.gif could not be uploaded. Only JPEG, PNG and GIF images are allowed.

It happens even though I have the paths in Configuration > Media > File System set to be inside the web root.

Public file system path: sites/[my directory]/files [permission 775]
Temporary directory: sites/[my directory]/files/tmp [permission 755]

It seems that Drupal tries to save a temporary file in /tmp/ although the temporary directory is set to something different.

How can I fix the problem to be able to upload a file?

The key here is that PHP is attempting to create the temporary file in a public directory. If you refer to the your PHP settings, find out what is specified for the 'upload_tmp_dir'. Use a phpinfo() call to display this, also available in the Status Report by clicking on the PHP version number. This directory has special privileges that open_basedir will not block. Set your drupal temp directory to this path explicitly and it should work.


What's the difference between enabling Node View (and adding a variant) and creating a new Panel page? To learn more about Panels, I've been repeatedly traipsing through screencasts by Shane Thomas and Johann Falk. Right now I find myself confused about the distinction between: enabling a copy of node_view so one can add a variant for a content type, and, creating a new panel page for that content type.

Code Karate's screencast series is directed to learning about Panels, but #129 takes a side-step into creating a copy of node_view Page (through Page Manager) to create a variant, selecting by content type. I wonder why Page manager is being used for a tutorial about Panels.

I want a page for a specific content type, but I would like to use a Panel page to get there. How do I do this?

I'm also not clear on what invokes a Panel.

Note: I've read this question/answer by @Letharion about the difference between Page manager and Panels which is a bit too high-level for me at this stage.

Page Manager allows you to intercept existing paths or create new paths in the system.

As the node view path already exists, and you want to change the way it operates depending on some conditions (bundle for instance) you need to enable a copy of node view path in Page Manager, instead of creating a new one (as it already exists you cannot create a new one as it will conflict)

EXAMPLE: For all nodes of bundle type Article, when the user attempts to view such an article, you want to perform some ACTION. So you override the node view path, create a variant that filters on bundle of Article, then perform some ACTION.

The ACTION is pluggable. You can do a redirect for instance. So when the user attempts to view an Article you intercept that, look at some context on the specific article (lets say there is an Entity Reference field to a Basic Page), then redirect to that Page.

Panels has a plugin component for Page Manager. So when your condition to view an Article for instance is satisfied in Page Manager (via your variant), you can select that Panels take over the rendering of the page.

The beauty of Page Manager is that it intercepts the requested page and then makes all kinds of context on that page available, such that you can make decisions (via created variants) on what to do, and when you for instance make the decision to pass the rendering over to Panels, you have all the context available to you. You can even load more context if you wish. On a node you have limited author information available such as the Users uid, but with Page Manager you can request that it pulls in the User entity to make other fields available such as email etc. You can continue to bring in related context in this fashion: think about the case of a node that has an entity relationship to another type of node that has an author (User) that has a taxonomy reference etc. Access to more context is very helpful. Think of the difficulty with a Views Block. It only has access to the menu object's key (node id etc) and url parameters. But in Panels (via Page Manager) you can embed a View Content Pane and pass as much context to it as needed.

SO in essence, the Page Manager - Panel relationship is merely the way by which you decide what paths and what conditions on that paths must be satisfied in order for Panels to take over the rendering with access to lots of context.


Breadcrumbs not showing properly translated I am using a multilingual site with an Arabic and English versions. Before it was showing properly, but after the menu has been translated to Arabic, the breadcrumbs are showing only in Arabic.

How can I get the breadcrumbs in English too?

the first you must check the node type that is not translated then you write the code like this

function YOURTHEM_breadcrumb(&$variables) {
  $breadcrumb = $variables['breadcrumb'];
  $breadcrumb[] = drupal_get_title();
  if (!empty($breadcrumb)) {
    $node = node_load(arg(1));
    $type = $node->type;
    if ($type) {
      switch ($type) {
        case 'conventions_exhibitions_director':
          $breadcrumb['breadcrumb']= l(t('Conventions Exhibitions Directory'), 'conventions-exhibitions-directory');
          break;
         case 'event':
          $breadcrumb['breadcrumb']= l(t('Event'), 'event');
          break;
         case 'news':
          $breadcrumb['breadcrumb']= l(t('News'), 'news');
          break;

      }

    //var_dump($breadcrumb);
      if($type == 'webform'){
        array_pop($breadcrumb);
        if (arg(0)== 'node' && arg(1) == 263){
           $breadcrumb['breadcrumb'] = t('Attend an Event');
        }elseif (arg(0)== 'node' && arg(1) == 7) {
          $breadcrumb['breadcrumb'] = t('Contact Us');
        }elseif (arg(0)== 'node' && arg(1) == 263 && arg(2) == 'done') {
          $breadcrumb['breadcrumb'] = t('Attend an Event');
        }elseif (arg(0)== 'node' && arg(1) == 7 && arg(2) == 'done') {
          var_dump($breadcrumb);
          $breadcrumb['breadcrumb'] = t('Contact Us');
        }
        $output .= '' . implode(' > ', $breadcrumb) . '';
        return $output;

      }
  }
    $output .= '' . implode(' > ', $breadcrumb) . '';
    return $output;
  }
}

be careful to replace the 'YOURTHEM' to your current them name


Unable to create new user from Admin "New User" page ... Drupal 7 function MODULE_NAME_form_user_register_form_alter(&$form, $form_state, $form_id) {
 $form['actions']['submit']['#value'] = t('Submit');
}

I override the name of the submit button using customs module.

User registrations works fine, but when I'm trying to create a user through admin interface, fill out the form and click "Submit", I get redirected to "user/list" page, user doesn't get created, and the text on the top of the page is actually from "create user":

Any idea why this problem occurs?

This is a core bug. You can read about it here. What you can do is to translate "Create new account" string or use String Overrides module.


How to get Media entity image (Entity Reference Field) URL in TWIG theme Apologies if this question has already been asked. However, in my research I found the answers have been for simple image fields which are in default install of Drupal 8. However, in order to have reusable media, I am using Media Entity and associated modules. The problem is I am not able to access image or its URL in TWIG template, where simple image fields work just fine.

While the code below works as expected if field_image is a simple Image type, but doesn't work if it is Entity Reference field.

<div class="header-title white overlay" style="background-image:url({{content.field_image.0}});">

In case of Entity Reference field, the output is fully escaped and breaks the structure of my theme. How can I get raw image or URL? I am not a programmer so I don't know how to write preprocessor code.

I am attaching configuration images for the Media Bundle I am using and the node configuration in which I'm using the two types of image fields.

Media Bundle configuration

Node configuration. Note, 'field_image' is default drupal image type, while 'field_image2' is an entity reference field as configured in the Media bundle above.

Please advice how to get this working. Thanks.

Drupal Configuration

Drupal 8.3
media_entity_browser-8.x-1.0-beta2
media_entity-8.x-1.6
media_entity_image-8.x-1.2
embed-8.x-1.0-rc3
entity-8.x-1.0-beta2
inline_entity_form-8.x-1.0-beta1
file_entity-8.x-2.0-beta3
file-8.2.6
field_formatter-8.x-1.0
image_raw_formatter-8.x-1.x-dev
image_url_formatter-image_url_formatter

If this entity referenced image is controlled by Media, then you should let normal rendering occur:

{{ content.field_image2 }}

The rendering is then controlled by the field formatter, which will look to a display mode in Media, which is not dissimilar from Node display modes (default, teaser, etc).

Your filename would be something like:

media--media-bundle--display-mode.html.twig
media--media-bundle.html.twig

The first one is most specific, the second one would be the base for that media entity wherever it is used. I usually opt for the first one.

It is in this specific twig template where that code should live. The markup should be sourced there, instead of the referencing entity, in my opinion.

You could also do some preprocessing to solve this as well. Here is an example:

/**
 * Implements hook_preprocess_node().
 * @param $variables
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node->bundle();

  if ($bundle == 'landing_page' && $variables['elements']['#view_mode'] == 'hero') {
    $hero_image = $node->get('field_hero_image')->getValue();

    if (!empty($hero_image)) {
      $entity = Media::load($hero_image[0]['target_id']);
      $variables['hero_image'] = ImageStyle::load('landing_page_hero')->buildUrl($entity->field_image->entity->getFileUri());
    }
  }
}

Then in my respective template...

<div{{ attributes.addClass(classes) }} style="background-image: url('{{ hero_image }}');"></div>

Alternatively, you can preprocess the media entity:

/**
 * Prepares variables for media templates.
 *
 * Default template: media.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - media: An individual media for display.
 */
function mytheme_preprocess_media(&$variables) {
  /** @var \Drupal\media_entity\MediaInterface $media */
  $media = $variables['elements']['#media'];

  $variables['media'] = $media;
  $variables['name'] = $media->label();

  // Helpful $content variable for templates.
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

  $variables['attributes']['class'][] = 'media';
  $variables['attributes']['class'][] = Html::getClass('media-' . $media->bundle());

  if (!$media->isPublished()) {
    $variables['attributes']['class'][] = 'unpublished';
  }

  if ($variables['elements']['#view_mode']) {
    $variables['attributes']['class'][] = Html::getClass('view-mode-' . $variables['elements']['#view_mode']);

    if ($variables['elements']['#view_mode'] == 'hero') {
      $variables['hero_image'] = ImageStyle::load('hero')->buildUrl($media->field_image->entity->getFileUri());
    }
  }
}


In Drupal 7, teaser view doesn't show the image filed because the image filed in the content type can have multiple images? I've added an image field in a content type, and set the 'Field Settings' -> 'number of values' to unlimited, which means users can upload unlimited images for this field.

then I build a view for this content type and expose the image filed to the view. what I 'd like is to expose only image in teaser view, and all images in the full view.

I use a template preprocess function

function MYTHEME_process_field(&$vars) {
  $element = $vars['element'];
  // Field type image
  if ($element['#field_type'] == 'image') {
    // Reduce number of images in teaser view mode to single image
    if ($element['#view_mode'] == 'teaser') {
      // something might be wrong here
      $item = reset($vars['items']);      // not working
      $vars['items'] = array($item);      // not working
    }
  }
}

In debugging this function, this 2 lines

  $item = reset($vars['items']);
  $vars['items'] = array($item);

doesn't seem to work. any suggestion?

The Display Suite Module offers you to choose the number of items to show on each viewmode.


Drupal sessions in angular app I'm developing an angular application which uses drupal as a backend. When user login to my webapp, they can able to get some data from the drupal backend. Also, I'm maintaining a session for that user in the drupal backend.

I want to get that session values of a user from drupal backend to my angular app. Is there any possibility to do this?

I didn't use any session data, but I have passed sections of Drupal.settings on into the Angular scope when declaring modules. It worked for my case. Here is an example:

angular.module('mypackage.name', []).constant('appConfig', Drupal.settings.custom_module.custom_module_config);

This lived within the libraries folder (attached to pages by Drupal) for 7.x.

But I am not sure that it really matters what backend you have here, this seems like an Angular question. Here is one that might help: https://stackoverflow.com/questions/14957450/maintaining-session-through-angular-js


Is there a function to return all the multisite names? Is there a Drupal function to return all the multisite names?

I have searched a bit but have not come up with anything.

Okay, this is what I am using for now in a drushrc.php file. If you can improve upon this please post a new answer. Thanks

// Gets a list of all directories in /sites.
$sites = glob(drush_locate_root() . '/sites/*', GLOB_ONLYDIR);
// Strips the absolute path except for the last name.
$sites = array_map('basename', $sites);
// Removes the 'all' folder.
$sites = array_diff($sites, array('all'));


Insert a countdown in each node based on a pre-existing date field I would like to put a countdown for each node using a field expiration date (whose values users have already entered).

I explain you my case:

My user publishes an event that have an expiration date (I already have many values for this field inserted by the users and some of them are of events still in progress).
I would like to insert a countdown in each page of the events, based on the expiration date inserted by the user and the date when the user has published the event on my website.

I tried with this module: field timer but I don't know how to do the connection between this module and the expiration date.

Thanks in advance for your help.

I assume you have two fields in one content type - countdown_date and expiration_date. Both values user has to insert manually. And after submit action, you want to assign expiration date to both fields, yes?

Read about hook_node_submit(). In your MYMODULE_node_submit($node, $form, &$form_state) you can check the type of content, then assign expiration_date to countdown_date. This method works with save and preview's action.

For more detailed answer I need more details about these fields.


Template page for specific node I have seen a ton of examples on how to do this and I must just be fundamentally confused. I want to modify one node, in my case nid 302998. I have tried:

node-302998.tpl.php
page-node-302998.tpl.php
node--302998.tpl.php
page--node--302998.tpl.php

All to no avail. I am placing them in my templates folder. In that folder I see a few working examples of tpl files, such as node--glove.tpl.php, glove being one of my content types, but I see no examples of specific nodes/pages.
I have tried clearing caches as well. I am out of ideas.

You can override every single node with its node id, as per your nid it should work with node--302998.tpl.php then also if its not working just enable debug mode so you can get idea how many template name available.

To enalbe debug mode open setting.php $conf['theme_debug'] = TRUE;
 refresh page again and press ctrl + U for view source.
 you will get all the name those are possible with your page.


Automatically generate a short description of a page when a user posts a link On facebook, google plus and similar websites, when someone posts a link, the thumbnail and short description of the page is automatically generated. See the screenshot below.

Is it possible to this in Drupal 7 ? If yes, how? Is there any module for it?

Look at the source for that page, you'll see this

<meta name='description' content='In honor of Wolfenstein 3D&#039;s 20th anniversary, the game will be released for free to play in browser today.'/>

Should be fairly straightforward to grab that!


Route not found error when using webform_rest to upload files I want to upload a file using webform_rest API as described here. #2899902. But it gives me 415 Unsupported Media Type error as you can see in the screenshot.

Here is my code

  methods: {
    addImage() {
      this.dropFiles = event.target.files[0];
    },

    submitResume() {
      const formData = new FormData();
      formData.append("image", this.dropFiles, this.dropFiles.name);

      axios
        .get("https://example.com/rest/session/token")
        .then(tokenResponce => {
          this.formToken = tokenResponce.data;
        });

      axios
        .post(
          "https://example.com/webform_rest/job_applications/upload/resume?_format=json",
          formData,
          {
            headers: {
              Accept: "json",
              "Content-Type": "application/hal+json",
              "Content-Disposition": "file; filename = full.pdf",
              "X-CSRF-Token": this.formToken
            }
          }
        )
        .then(response => {
          this.submitForm(response);
        });
    },

    async submitForm(response) {
      if (this.page === "singlejob") {
        var position = this.jobs.title;
      } else {
        var position = this.position;
      }

      let config = {
        headers: {
          Accept: "json",
          "Content-Type": "application/hal+json"
        }
      };

      this.isLoading = true;

      axios
        .post(
          `https://example.com/webform_rest/submit?_format=json`,
          {
            webform_id: "job_applications",
            name: this.name,
            email: this.email,
            position: position,
            resume: response.data.fid[0].value
          },
          config
        )
        .then(response => {
          this.isLoading = false;
          if (response.data.sid) {
            this.$router.push({
              path: "/thank-you"
            });
          }
        })
        .catch(error => (this.isLoading = false));
    }
  }

Need help here.
Thanks

I got it working. two things I was missing.

Make sure you accept all the operations / JSON requests from here
/admin/config/services/jsonapi
I was confused with "binary file data". So basically you don't have
to do anything with the file. No formData, No base64, just pass your
file variable as it is.

And it worked.

Thanks


Commerce License not de-activating when expired I'm using commerce license on one of my website. And I found out that some of the licenses that are expired didn't get de-activated.

As you can see, in the image below. License 113, 114, 115 should be inactive. But they are still Active (Actief). In the last column you will see that the expiring dates are past today (08/22/2016).

Using the modules Ultimate Cron and View Queue I'm able to see that the Commerce License module is adding the queue.

I also look in my logs but no errors are found. Does anybody know what the problem can be or what my next step in searching for the problem can be?

Thanks in advance,
Zeb

For some reason the basic Drupal cron didn't call the license sync. Using Ultimate Cron I was able to make this work.


Save paragraph widget data in custom form I am adding a node field widget in a custom form as described here and my code is:

$site_settings_node = Node::load($node_id);
$entity_form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')
  ->load('node.node_type.default');
if ($widget = $entity_form_display->getRenderer('field_my_field')) {
  $items = $site_settings_node->get('field_my_field');
  $items->filterEmptyItems();
  $form['#parents'] = array();
  $form['custom_form_field'] = $widget->form($items, $form, $form_state);
}

How do I update the paragraph field values in my submit handler? Is there something like the below that I can do?

$widget = $entity_form_display->getRenderer('field_my_field')
$widget->submit($items, $form, $form_state);

I found the solution via this article. Though for the solution to work specifically for the paragraph field, I had to add a patch for an issue discussed here.

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#parents'] = array();

  $node_id = 1; // Some node
  $entity = Node::load($node_id);
  $form_state->set('entity', $entity);

  /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
  $form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')->load('node.node_type.default');
  $form_state->set('form_display', $form_display);

  foreach ($form_display->getComponents() as $name => $component) {
    $widget = $form_display->getRenderer($name);
    if (!$widget) {
      continue;
    }
    $items = $entity->get($name);
    $items->filterEmptyItems();
    $form[$name] = $widget->form($items, $form, $form_state);
    $form[$name]['#access'] = $items->access('edit');
    $form[$name]['#weight'] = $component['weight'];
  }

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

public function submitForm(array &$form, FormStateInterface $form_state) {
  /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
  $form_display = $form_state->get('form_display');
  $entity = $form_state->get('entity');
  $form_display->extractFormValues($entity, $form, $form_state);
  $entity->save();
}