Userpoints Karma - Is it possible to only charge user points for down votes? I'm using the User Points, User Karma, Vote Up/Down modules. I wonder if there is a way you can configure it to only deduct user points when you vote something down and not up.

Similar to Stack Exchange's reputation system: if you vote something up, you don't get docked, but if you vote something down you get docked reputation points.

Using the Reputation User Points -> Karma Points -> Voter Points Cost setting, I am only able to configure it to charge if you vote at all, regardless of the direction of the vote. Any ideas?

Adding a module to override User Karma's settings is certainly one option.

Another possibility is to use Rules and Voting_Rules to control your own settings for adding and subtracting user points.

Once enabled you go to /admin/config/workflow/rules and "Add New Rule".  Set it up to React on Event "User votes on a Node".

Add the condition "Check the value of the vote" and if less than 0 add an Action to "Grant points to a user" but make them negative points.

Here's a screenshot of this Rule:

Optionally, if you want to use User Karma in conjunction, you could instead React on the Event of "User was Awarded Points" and test for Conditions and override where appropriate.


Can I invoke a template for print media? I have a node type that is usually viewed as a web page but the client requires that occasionally it is also printed out in hard copy.

There is quite a lot I can do with css and media queries for print media but I would ideally like greater control over the content through the page templates.

As far as I can tell, there are no special theme suggestions for print and that theme functions, hooks, and templates are not aware of the target medium, be it screen or print.

This is a Drupal 8 project and whereas there were some Drupal 7 modules for print that might have been worth investigating, there doesn't seem to be anything right now for D8.

I any case, getting control over the content in a twig template would be quite sufficient if only I could tell that it was being rendered for print rather than screen.

You cannot tell in drupal, if your page is going to be printed.

CSS and media queries is browser based. You deliver the same content (html) and the browser will generate different output for display and print.

If you want to do deliver a special print version, you have to provide a different url for this and link it on your page, for example a print button. You can then check in the twig for the special url and change the html.


How to modify HTML of specific node in Drupal 7? I use Drupal 7 with Bootstrap Theme. I have many blocks placed on different nodes and HTML generated is as follows:

        [...]

    [...]

    [...]

    [...]

    [...]

I want to change that HTML for put some
 to enclosing some <sections>

Example:

      [...]

      [...]

Short answer: Place a customized template named node--[nid].tpl.php or page--node--[nid].tpl.php in your themes template folder. ([nid] = id of specific node).

Long answer: If you didn't done yet, you should first create a Bootstrap subtheme for your modifications. Then copy either node.tpl.php or page.tpl.php from the Bootstarp theme inside your subtheme folder. Rename the file to either node--[nid].tpl.php or page--node--[nid].tpl.php (Replace [nid] with the node id of the specific node) and customize the file to your liking. Lastly clear the cache at /admin/config/development/performance

For more/other template examples have a look at Drupal 7 Template (Theme Hook) Suggestions

EDIT: To control specific blocks for a specific page, I'd create a dedicated region inside your subtheme's .info-file and in your page.tpl.php / page--node--[nid].tpl.php. And place the blocks inside those regions.


How do I get view mode Is there an easy way to get node's view mode from entity.view?

function classier_preprocess_views_view(&$vars) {
    $vars['rows'][0]['#rows'][0]['#view_mode'];
}

If you're trying to get the view mode of a node you probably want to use a different hook.

function classier_preprocess_node(&$vars) {
    $view_mode = $vars['view_mode'];
}

Should do the trick.


How to show Total with taxes at admin/commerce/orders when order status is Review (using Commerce)? I need  to show Total with taxes at admin/commerce/orders using Commerce.
Here the orders are shown without taxes, how can get to show the total including taxes?
I didn't see anything like a Total with taxes in the view fields.

UPDATE 2 I need that the system show the taxes when the order status is Review It seems to me that the taxes are added when the status is Completed. or Pending. See my first capture.

Update 1: I also see that the taxes are not shown in admin/commerce/orders/XX nor in admin/commerce/orders/XX/edit. How am I supposed to see the taxes for the order?? This can't be right.

Capture with PENDING status

You can use the Commerce price by components module.

  Extension to Drupal commerce that provides a price formatter to
  enable/disable price components such as discounts or taxes when
  displaying prices. This gives the admin absolute control over which
  components should be displayed and which shouldn't. It also provides
  two Views handlers to display/hide price components in cart totals and
  order totals. Additionally it has basic rules support that gives to
  the commerce administrators the ability to do conditions using price
  components such as discounts or taxes and react accordingly.

Install the module and change the commerce total field of the view with this one.


Trigger jQuery "add more" multiple times I have a form that I am filling with default values in hook_form_alter. Some of the fields are in a in a field group and I need to trigger the "add more" button using code.

I figured out how to send a value to the jQuery code via $form['#attached']['js']. I thought I could use that value to run a loop in the jQuery to trigger the "add more" as often as necessary but I only see the field group values twice.

For example if there should be four sets of field group values, I will see the first and second one but not the third or fourth. If I click on the add more button two more times I'll see them in the form.

Here is the code in the js file:

(function ($, Drupal) {
  // Custom functions and variables can go here
  Drupal.behaviors.example = {
    attach: function (context, settings) {
      // Put your document's onload code here
      //alert(Drupal.settings.example.clicks);
      for (var i = 0; i < Drupal.settings.example.clicks; i++) {
        //alert(i);
        $("#edit-fgm-node-example-form-group-stuff-add-more").trigger("mousedown");
      }
    }
  };
}(jQuery, Drupal));

This where I attach the js file

function example_after_build($form, &$form_state) {
  // TODO: Stuff!

  $settings['clicks'] = $_SESSION['count_of_items']; //the initial count of times to trigger jquery
  drupal_add_js(['example' => $settings], 'setting');

  // Add our JavaScript file, named after_ajax.js. This file
  // lives in the /js folder inside our module:
  $form['#attached']['js'] = [
    [
      'type' => 'file',
      'data' => drupal_get_path('module', 'example') . '/js/after_ajax.js',
    ],
  ];
  return $form;
}

Any advice on how I could trigger the "add more" multiple times? Or is what I want to do not possible?

It is possible that the ID of the "Add more" button you're targeting is changing as the first AJAX request comes back (the form will be rebuilt, so IDs of all elements will change). Try changing '#edit-fgm-node-example-form-group-stuff-add-more' to a class-based selector.


Save content with current user roles and add filter to show only content with current user role Using drupal 7,
when creating new content of the type "Document"
the current user roles must be added so I can later on show only Documents of his current role.

For example, we have the following user: this is Jake, he is a Firefighter. He creates a document about the dangers and pitfalls of being a firefighter. This is only relevant for Firefighters. So in the list of documents (view) I want Jake and all other Firefighters only to see Firefighter Documents.

So if Jake create new content of the type "document" I want to add his user roles
and later on add a filter in the view so only Firefighters get to see Firefighter Documents

I want to have the following filter for the list Document view:

Published = true
Content type = Document
User role = current user roles (Firefighter in this case)

Access must be restricted for every user based on their role.
For example, Jake the Firefighter is not allowed to view Policemen Documents

You don't have to add author's role to a node directly.
You can add user's role based Exposed Filter option in a view by using relationship. To do this please follow steps of below:

Create your view as usual (like configure view name, display type
etc)
From Fields section add all desire fields.
From Filter Criteria choose appropriate node type.
Click on the Advanced button (indicated by an arrow on right side of the view).
Click on the Add button of the Relationship section and add Content: Author as a relationship.
Now Click on the Add button of the Filter Criteria section and add User: Roles as a filter. In this filter settings pop-up form, enable or check Expose this filter to visitors, to allow them to change it option then choose Is one of option as an operator.

Output/result:


How do I add a specific meta-tag to all the pages of a site? I want to prevent Google from indexing my website. I know I need this meta tag added to the header.

<meta name="robots" content="noindex" />

How can I add this meta-tag to all the pages of a site?

You can use the Metatag module for this, in order to add meta tags to every page of your site:

If you want to do it by coding, it is possible to implement the theme_preprocess_html hook to add the meta tag manually:

function theme_preprocess_html(&$variables)
{

    $noindex = [
            '#tag' => 'meta',
            '#attributes' => [
                'name' => 'robots',
                'content' => 'noindex',
            ],
        ];
    $variables['page']['#attached']['html_head'][] = [$noindex, 'noindex'];
}

(more details here: https://stackoverflow.com/questions/35913739/add-meta-tag-to-head-in-drupal-8)


Field Type list in module creation I'm trying to adapt the next code from the book:
http://www.amazon.es/Drupal-Development-Experts-Voice-Source/dp/1430228385/ref=sr_1_1?ie=UTF8&qid=1327316185&sr=8-1

function _job_post_installed_fields() {
  $t = get_t();
  return array(
    'job_post_company' => array(
      'field_name'  => 'job_post_company',
      'label'       => $t('Company posting the job listing'),
      'type'        => 'text',
), );
}
/**
 * Return a structured array defining the field instances associated with this content type.
*/
function _job_post_installed_instances() {
  $t = get_t();
  return array(
    'job_post_company' => array(
      'field_name'  => 'job_post_company',
'type'
'label'
'widget'
'type' ),
  => 'text',
  => $t('Company posting the job listing'),
  => array(
=> 'text_textfield',
      'display' => array(
        'example_node_list' => array(
          'label'       => $t('Company posting the job listing'),
          'type' => 'text',
        ),
), ),
); }

But I can find anywhere a list of types I kind use instead of "text".

My question is:
Can you help me find a place where I can find a list of possible images?
How that code would be if I wanted to create an image field, or a tag list field?

Thanks

For field definitions, I find that the easiest thing to do, is to create the field in the UI and fetch the definition using field_info_field and field_info_instance and then dump the variable using the devel module (dpm) oe something similar.

Alternatively you could browse code, field types are defined in hook_field_info and widgets are defined in hook_field_widget_info (the form for the field) and formatters are defined in hook_field_formatter_info (how fields are rendered).


How to make Panel Page variant selection rules detect URL parameter? On D7 I have set up a new panel page variant and want to use it with a certain selection rule:

 String: URL path   Current path is "*/cars/*?buy"

Eg I want this panel variant to be used if the URL is new/cars/honda?buy.

However the above doesn't work. Adding ?buy to the url doesnt trigger it to be used.

Would anyone know a way to set selection rule so that I can use this page variant with a give parameter in the URL?

I found the Selection Rule Query string exists does this.


Error while updating Updated Drupal from 8.7.8 to 8.8.0 with:

composer update --with-dependencies

That part went well, but when I run:

drush updb

I get following error:

In ProcessBase.php line 188:

  Unable to decode output into JSON: Syntax error

  Error: Call to a member function getConfigDependencyKey() on null in Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid-
  >calculateDependencies() (line 394 of /var/www/html/drupal/web/core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndex
  Tid.php).

Checked the code a bit and it goes like:

  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();

    $vocabulary = $this->vocabularyStorage->load($this->options['vid']);
    $dependencies[$vocabulary->getConfigDependencyKey()][] = $vocabulary->getConfigDependencyName(); // <-- line 394

...

And $this->options['vid'] is empty and $vocabulary var becomes null.

Any idea what's wrong here?

just to make you aware in case you're using the Pathauto module and you didn't notice:

  Changes to path aliases and a critical note for sites using the Pathauto contributed module
  If you have the contributed Pathauto module enabled, you must update to the latest version of Pathauto before you update to Drupal 8.8.0. Failure to update Pathauto before updating core could result in data loss. Drupal 8.8.0 declares a conflict with Pathauto 8.x-1.5 or lower for this reason.

https://www.drupal.org/project/drupal/releases/8.8.0

Can't say anything about your specific error though.


hook_form_alter selecting a default value in a node reference select list I am trying to add some logic to auto select a node reference option on a select list on my content type. I am trying to set it with the following.

$form['field_my_field']['#default_value'][0]['nid'] = 5;

Where 5 is a nid. The value is set correctly in the form but when it is rendered to the page the option in the select list is not selected.

What am I doing wrong?

CCK requires a little voodoo to alter values with a hook_form_alter(). You need to implement a special type: after_build, so put this code in a custom.module:

//Declare the callback for after_build for page node form
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'page_node_form) {
    $form['#after_build'][] = 'custom_after_build';
  }
}

function custom_after_build($form, &$form_state) {
  //Set my node ref to 5
  $form['field_node']['nid']['nid']['#value'][0] = 5;
  //you can set more than one using
  $form['field_node']['nid']['nid']['#value'][2] = 6;
  //have a look at the form after after_build
  dsm($form);
  return $form;
}

I adapted a previous answer of mine, but I have to admin that node reference is even more confusing ;)


Correct way to render an custom entity and its custom field? In my module, I have a custom entity LocationEntity and it uses a custom field type CoordinateItem which has 2 sub fields X, Y.

So what is the correct way of Drupal 8 to:

1) Render this LocationEntity in a twig template?

What I'm doing is just send the entity to twig template '#loc1' and manually render its each field value using getter method {{ loc1.getName() }}. It works but I'm sure this is not the correct way to do.

2) If question 1 has another correct way then how to have more than one templates for rendering the entity?

For example, one simple layout with less fields and one detail layout with all fields.

3) In the entity, I defined to use the custom field CoordinateItem. But now what to do with its getter and setter, because it's not a single sub field inside?

Getter if $this->get('coord') -> a FieldItemList object.
Getter if $this->get('coord')->value -> null.
Setter? What type is the parameter?

4) I wrote a formatter for CoordinateItem to show its sub fields. But again I don't know how to use this formatter to render this custom field in the main (entity) template?

Maybe this is related to question 1 and 2?

View Builder

Set the view_builder in ContentEntityType annotation to EntityViewBuilder to inherit some default behavior (or write your own).

Set your canonical router to something like what content_entity_example does in the examples module.

Berdir suggests using DefaultHtmlRouteProvider though that class is marked as @internal so it may not be stable to use long term.

content_entity_example.routing.yml

entity.content_entity_example_contact.canonical:
  path: '/content_entity_example_contact/{content_entity_example_contact}'
  defaults:
    _entity_view: 'content_entity_example_contact'
    _title: 'Contact Content'
  requirements:
    _entity_access: 'content_entity_example_contact.view'

Change your entity theme to something like what node module does, and have it display as a render element.

Use your entity or bundle's field display page to change what field formatters a given field will use.

Then you can print out {{ elements }} in the template for it to go through the entire render array for a given view mode. Again, you can follow something similar to node module.


Create the pdf version of a node programatically (and attaching that pdf version to that node) I have installed the print module. Every time I create a node of type X a print version can be generated each time I click the print link.

The thing is that I need that pdf to be generated programatically, and not by hand every time I click on the link.

I need (I´ve tried with rules module, without any success) to create the pdf version of that specific nodetype X, and attach that pdf version to the node that is being created.... without me clicking to the print link, downloading the file, editing the node and then attaching that file to it.

Is there a way to do that?

Thanks for your insight!!!

Rosamunda

You can could start by taking a look at the PHP PDF extension and see how that works out for you. If it does, then you can implement a hook_node_save() - assuming you are in D7, and every time that a node is saved, call your custom PDF functions to generate the PDF.

After your PHP PDF implementation creates the PDF file, you should use Drupal's File API to place the file in the proper place. You would use the File API because it creates an entry in Drupal's file table, and it automatically handles permissions for you - so you can for example, support both public and private (session-protected) files.

Once you upload the file to your web server with the File API, you can then use the Field API to put a reference to the newly created PDF file in one of your node's custom fields. The node's custom field would be of type "file field", and what you would save to that field programatically is the newly created file's fid. The Field API will provide you with the fid.

Finally, you will need to implement a theming function that accepts the node id as a parameter, loads the node in question, looks for the custom field holding the file (using again the Field API), turns the fid inside that custom field into a link with the proper access-level (using the File API), and returns the themed link to your theming layer so it can be printed with the page, and clicked with the users.

In conclusion, unless somebody suggests a contrib module that does this, you would end up implementing at least two Drupal APIs, one external PHP API, and creating some theme hooks. If you are an experienced developer, it should take at least a few hours (or a pair of days).


The uploaded file likely exceeded the maximum file size (32 MB) that this server supports on remove image In my taxonomy terms,when I try to edit a term I got this error :

  An unrecoverable error occurred. The uploaded file likely exceeded the
  maximum file size (32 MB) that this server supports.

even though I didn't try to upload a file,I tried to remove the uploaded file.
and I don't have mod_security module enable on my server .( as I search through google,there was problem with mod_security apache module and ajax).

I have no idea why this is happening only on particular vocab terms,not in anywhere else.

For sure this is due to some problem with your sever setting, contact your webhosting company and talk with them regarding the issue.

It could be due to ModSecurity which is an  is an open sourceweb application firewall Apache module. which help in providing an external security layer that increases security, and help in preventing attacks.

The other reason could be the size your allow to upload that can be change in your server setting. It is also important to check apache max_execution_time.

If you have control over your server then you can try to change your php file

post_max_size = 128 MB
upload_max_filesize = 32MB


How can one automatically rename files uploaded in a webform? I would like to rename the files uploaded to a webform according to some tokens or the value in some other field.

I did some research on this and was surprised to find no definite solution.

For example:

https://www.drupal.org/node/326738 => A patch supplied for token support but the discussion ends without a final working patch
https://www.drupal.org/node/364752 => Discussion on "Renaming file upload fields using other form fields". Discussion ends in "Won't Fix"
Webform, creating customized directories for uploaded files => Approaches have been suggested here but no final solution given.

The sandbox project is removed as the issue queue get continued, the latest patch has been failed in simpletest, but you can still check this patch


Requirements issues while setting up a D7 website I'm trying to set up an old D7 website, but I stumble upon some issues.

As you can see in the image below, I work with PHP 5.4.8 and Apache 4.2.3.

I don't use things like XAMPP. I've configured Apache, MySQL and PHP myself on my Windows 7 machine.

In my php.ini-file I've enabled all the necessary extensions I believe...:

extension=php_bz2.dll
extension=php_curl.dll
extension=php_gd2.dll
extension=php_gettext.dll
extension=php_imap.dll
extension=php_mbstring.dll
extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_openssl.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll

But still, I get the errors above. What should I do next?

Looks like you're missing some PHP components.

Try the following on the command line:

sudo apt-get install php-gd php5-common php5-mysql
sudo service apache reload

EDIT

I've just realised I've COMPLETELY assumed you're running *buntu - if you're not then please let me know!


User password valid only for one day When users forget their password they click on the reset password link. There, they enter their username, or password, and a mail goes to their inbox, instructing them on what to do.

The instructions say to follow a link that resets the password, and then redirects them to their user profile to enter a new password. Although they enter a new password, the next day (and everyday) the system doesn't recognize the password, and they have to reset it again.

Why does this happen?

How does the "reset password" work? Does it check the access date to see if the day has changed, or does it use some kind of flag to let the system know the password is valid only for one day?

Finally the problem in my case had to do with the text that was sent with mail after user registration. When user was registered a mail was sent in his inbox with his username and a (system created) password. Then the text was providing a link to the login page, a second one linking to the auto log in page (where the user supposedly would not have to enter his password) and a third one that it is irrelevant.

So i realized that the second link was actually a link to reset your password if you forget the old one. So the user when first reading the mail he click on the second link to log in automatically but he doesn't know that the password given to him was reseted and now his log in was valid only for one day or for one use. Each time he has to reset his password.

Anyway if you have access to your database you can experiment to see if it is another issue for you. You can create a fake account in drupal. In the mail that is sent to you click the second link (something like http://mysite.com/foo/user/reset/1085/1349294892/7bc9baf9d42aa774be00a0f36090323f). Then go to table 'user' of the drupal database, find the fake user you created and modify the record of the column 'created'  and put a unix-timestamp older than a day (there are online unix-timestamp creator). This way you can experiment if the password is temporary or not.


Previous month in sql I have sql, where I need to select data for this month and data for previous month. How to do extraction od previous month data?

In my block in build() functionI have this:

//...
if ($what == "en_flip_per_month"){

    list($m, $y) = statistics_data_for_block('monthname', 'year');

    $sql = $connection->select('node_field_data', 'nfd');
    $sql->addExpression('COUNT(nfd.nid)', 'counting');
    $sql->where("nfd.langcode='en'");
    $sql->where("FROM_UNIXTIME(nfd.created, '%M' ) = ".$m."");
    $sql->where("FROM_UNIXTIME(nfd.created, '%Y' ) = ".$y."");
    $sql->groupBy('nfd.langcode');
    $sql->orderBy('nfd.created', 'DESC');
}
//....

and in my .module file I have this:

function statistics_data_for_block($m='', $y=''){
    $month = '';
    $year = '';

    //current
    if ($m == "month"){
        $month = "MONTH(CURRENT_TIMESTAMP)";
    }
    if ($m == "monthname"){
        $month = "MONTHNAME(CURRENT_TIMESTAMP)";
    }

    if ($y == 'year'){
        $year = "YEAR(CURRENT_TIMESTAMP)";
    }

    //... SOMETHING FOR PREVIOUS MONTH ...

    return array($month, $year);
}

So, I need a way to extract MONTH, MONTHNAME and YEAR of (CURRENT_TIMESTAMP - 1 month).

There was this one solution - use of SET and DECLARE, but how can it be done in Drupal 8 dynamic query?

Thanks

Not really related to Drupal, but this works on mySQL

MONTH(NOW() - INTERVAL 1 MONTH)
MONTHNAME(NOW() - INTERVAL 1 MONTH)
YEAR(NOW() - INTERVAL 1 MONTH)


Custom redirect after "admin create user" For usability of the system when a admin role creates a new user. The admin wants to edit user details but to do this he/she now needs to go to the user and click on "Edit" first.

Is there a way to redirect to this created user's "Edit" page immediately after creating that user?

Thanks in advance!

Try to use Login Destination module. This may solve your query.

Or you can do this by using Rules module.


How to make vertical tabs display on a custom entity? I have a custom entity in Drupal7 created using the Entity API. I am attempting to make it work with the meta tag module. I have added

'metatags' => TRUE

to hook_entity_info, and metatags display as a field under "manage fields" for the entity. The trouble is that the vertical tabs that usually display on every node do not show up on the entity. Thus, I have no way of changing any of the information in the meta tag field on the custom entity. How do you make the vertical tabs appear when using entity api?

This seems to be the reverse of the question remove vertical tabs, and should have a very similar answer.  In the documentation for the vertical tabs module, the first code snippet is how to enable vertical tabs on any form.  The second snippet looks more appropriate, as it is how to enable tabs from your custom module that creates your custom entity.

<?php
$vtabs = variable_get('vertical_tabs_forms', array());

// Enable vertical tabs on a form.
$vtabs['my_form_id'] = TRUE;

// Disable vertical tabs on a form.
$vtabs['page_node_form'] = FALSE;

// Enable vertical tabs but be selective of which fieldsets are included.
$vtabs['page_node_form'] = array('menu' => FALSE);

variable_set('vertical_tabs_forms', $vtabs);
?>

Edit:

The site variables here is a huge array that is always accessible to drupal.  Some of these settings can be stored in your site's settings.php file, as this variables array is present even there.  However, because of the nature of the change that you desire, I think the best choice for you is to have a hook_install in the module that defines your custom entity.

Assuming module name "your_entity", add a file "your_entity.install" to the module.

function your_entity_install() {
  // Enable vertical tabs on entity form.
  // this is supposed to be true as long as this module is enabled
  $vtabs = variable_get('vertical_tabs_forms', array());
  $vtabs['your_entity_form'] = TRUE;
  variable_set('vertical_tabs_forms', $vtabs);
}

Then disable and re-enable your module.  These variables can be set in the form_alter, but that would only be recommended if you needed the value to change based on other information that is not present at an earlier time.


How to get user data by providing user name or user profile field I am using postman. I want to provide the username or a user profile field say roll no and fetch the user's information. What should be the URL.

I am able to fetch the user information when I provide the uid using the following URL :

http://[yourdomain]/[endpoint]/user/[uid]

If you want to get the user data by providing username, you can use pass name (username) as a parameter to the service URL like follows

http://example.com/<endpoint path>/user?parameters[name]=krishna

If you want to pass either username or other user profile fields you can achieve that using Services Views module. After installing this module make sure to enable it under service resources list.

Create a view with contextual filter(s)

Executing view via views resource

After enabling "views" resource in your services endpoint you can do GET request to:

http://example.com/<endpoint path>/views/<view name>

This will execute a view and pass results.

Possible arguments:
- display_id: views display

args: array of view arguments
filters: array of view filter values
offset: views offset
limit: limit views number of results
format_output: boolean whether we would like to get themed view or data


How do I display Search API Facets and Openlayers Proximity search in one view? I am trying to add search facets to a specific views page that uses the openlayer proximity filter. So far I can only show facets in a view if I create a new view showing the search index I created in the search api.

If I chose to show 'node' or anything else other than a search api index, no facets will show up.

Now I am using openlayers proximity filter. This option again is only available if I chose show 'node' when creating a new view.

How do I get to display both my facets as well as the proximity filter in a view?

The "facets block" type that drunken monkey mentions on the issue you link to, is simply a type of views "Display", you can see below where you add one:

I haven't used the proximity filter, nor much of Search API, so I can't really give you an answer with better details. It seems to be like drunken monkey has actually answered the question in the issue queue, and perhaps you need to specify more precisely where you have a problem, to get better help.


Is --overrides an accepted option in drush 8.x? I'm creating a build script and would like to include the --overrides flag as describe in the documentation. I'm using Drupal 8.0.0 and Drush 8.0.1 and I get the following:

drush make build.make.yml ~/Sites/built --prepare-install --overrides=dev.make --no-cache -y -vvv
Unknown option: --overrides.  See 'drush help make' for available options. To suppress this error, add the option --strict=0.

Am I missing something? Is this functionality not built yet?

It appears to be in the master branch, but not yet in 8.0.x.


Bootstrap load theme locally How do I load the Bootstrap theme (css, js, fonts) locally?

I've searched around the drupal stack exchange, but every suggestion I've come across doesn't solve the problem. It seems like the other option is to create a sub-theme, but I'm not even sure if that will load all the necessary files for bootstrap locally/offline. The whole purpose of this is to load the bootstrap theme and its css/js/fonts without using any internet.

The issue is that I'm seeing the error as another user did like this:
https://www.drupal.org/files/issues/screenshot_218.jpg

There are answers like these below, but there has to be a way to do it without more installation other than drupal modules:
https://www.drupal.org/node/1978010
Using own Bootstrap 3 files

You can download bootstrap package and include it in your theme folder.

and go to admin/appearance/settings/bootstrap
then go to 'Advanced' and change CDN provider to custom.
give your local bootstrap css,js urls.

if you need to import it to a custom theme you can add it the bootstrap package like below.

your_theme.info

stylesheets[all][] = css/bootstrap.css
scripts[] = js/bootstrap.min.js

define the regions you need in your custom theme info file.

remmber to use the 'https://www.drupal.org/project/jquery_update' module for JS.


How to Display "Tabbed" content from Views in Panel / Pane in Node Template I would like to add a pane with tabbed content to a specific content type/Product display.

Using the guidance provided on drupal.org/node/2209747, I built a series of tabbed content in Views, using "Menu Tab" and creating new pages. (No problem, but not where I want to display the views.)

My goal is to embed this tabbed content into a pane (in Panels Node Template). However, when I select the view, I am required to specify either "Master", "Page 1", "Topic A", or "Topic B".

These options remove the tabs and either show all content (Master/Page 1) or filter content (Topic A or Topic B).

Is there a way to embed the tabbed view using only the Views module?
Should I create a Content Pane, instead of a page?
Can I avoid using an additional module like Quicktabs?

I assume that I am running into trouble because the tabbed view depends on the url path differentiation and cannot work when dropped into a pane. (At least with my current approach.)

Any help is appreciated!
keb

In the end, I used the "Panel Tabs" module. It is available in dev version, which gave me pause, but it works well on the main platforms (Chrome / iE / Firefox); I haven't played around on Safari.

With a little css, this will be a good working solution, but I would be interested to know if others have a more standard approach.

Thanks,
keb


Changing Column width of a table view (Drupal 7 Views 3) I have a view with 4 columns.  The first column, which contains a majority of the text is taking about about 80% of the width of the form and forcing the 2nd, 3rd, and 4th rows to wrap.  Problem is those columns have content that should not really be wrapped
for exmaple Tues 3pm - 5pm ends up looking like

Tues

3pm -

5pm

So rather than the columns adjust based on content, I'd like to manually set the width of the first column so that it leaves enough space for the others.  Or if need be manually set all the column widths.

Please understand I am totally lost in drupal and only have a small amount of css/php knowledge so please be as absolutely descriptive as possible.  I've found a bunch of examples in other areas but people have left out huge chunks of the code, or where it's supposed to go etc.  One place kept says "make changes to the css", not sure if it's normal but I have about 25 different css files in my drupal install, I had no idea WHAT css to make the change in.

Thanks in advance for any help!  This is a great community and I'm happy I went with Drupal because of it.

A more general approach than useful answers from @Michael Greisman @Neograph734 is to create some utility CSS classes that can be deployed on any View. That means if this requirement comes up when creating a new View, you already have a solution ready to deploy.

This is something that has been really helpful on a site where I have configuration responsibility but all template / CSS work is done by a contracted developer (who suggested this approach).

Create some CSS classes that can be used to fix column widths. In our case, using % values worked best, but do whatever makes sense for your site. Example:

.fix-width-20 {
width: 20%;
}
.fix-width-40 {
width: 40%;
}
.fix-width-50 {
width: 50%;
}

On a view with the table format, go to the 'Style settings' for the Field that is populating the column (or columns) where you want precise control of column width. Add the name of the CSS class that fixes the width. Example:


How to use picture element as background image? With the simple image field we are able to set the image style and use that to set the image as a background for a div tag (see example below). HOwever, as Drupal 8 has Responsive Image module, the image field will generate like below. With different breakpoints, different images are fetched by the browser, but this make it difficult to set the image as a background.

The current implementation is flexible because as the text grows so does the height of the div containing the image as a background image.

How would you use the picture tag to set the image as a background? I have not found a way to have Drupal detect what image is being fetched by the browser.

Goal:

Have image as a background
Overlay text on top of image
As the overlay text grows, so does the div containing the text. As such the image as a background should grow as well.

Current implementation without Responsive Images:

Authoritatively reinvent magnetic ROI without excellent interfaces. Professionally drive extensive manufactured products through 24/365 leadership.

Responsive image outputs which makes it difficult to set the background image (banner_large, banner_medium, banner_small are image styles)

<picture>
<source srcset="/sites/default/files/banner_large/name.jpg 1x" media="all and (min-width:1200px) type="image/png" >
<source srcset="/sites/default/files/banner_medium/name.jpg 1x" media="all and (min-width:768px) type="image/png" >
<source srcset="/sites/default/files/banner_small/name.jpg 1x" media="all and (min-width:320px) type="image/png" >

</picture>

Found that we can modify the responsive-image.html.twig to do what we need. We used a combination of the following links:

Responsive images
Responsive images (MDN Web docs)


How can build a website for multiple organization? I am going to build a Drupal 7 website with this structure.

Drupal admin create organizations, the organization is separated.
In each organization, it will be have an organization admin who is
assigned by Drupal admin.
Each organization will have their own taxonomy. The taxonomy are
created on one vocabulary.
Organization admin is able to create Project.
Organization can create users (called organization user) in their
organization and assign what project users can working on.
Organization users can create some nodes and those nodes are
separated in each project they are working on.

My questions are: 1) How I can do like that? and 2) What modules can be used to do it?

This is pretty much exactly what the OG (Organic Groups) module is for.


Custom content for several Spanish speaking countries I am on Drupal 7.

I need a website that will have different versions for each country in Latin America, where many countries speak Spanish. I was considering using one language per country, but as far as I am concerned, Drupal has only one Spanish version. At least, it doesn`t have one Spanish for Costa Rica, another to Honduras, Panama, El Salvador, Colombia and so forth. So I was considering creating one flavor of Spanish per country in Drupal (I would create new custom languages like "es-country code") and loading all the Spanish vocabulary again and again into these alternative custom languages. Do you think this approach works? I would like to take advantage from the fact that when using localization (i18n) you can set one single structure/navigation for the website accross the languages. The content across different countries will usually be the same, but sometimes it will be different. Working with i18n I can duplicate content accross the countries and change the small details wherever I need.

So my question isn`t technical, but broader. Do you think this approach is good? Which strategy/approach would you use if you needed to content customization per country where some of these countries speak the same language? Thank you

I think it's the best solution, or at least we used the same. In Switzerland, we have the Swiss German, that is a little bit different from German.

So we took the German translation as a base and created another language, like de-ch. Then with i18n and all other modules, we translated the differences.


What happens to the return array of hook_views_default_views after the function finishes? hook_views_default_views returns an array of $views objects. Immediately after that function has finished, where does it send the $views object it returns?

Obviously that array is passed to another function where it's iterated over and something is done with the data. That's what I want to investigate - what views is doing with the data.

I checked views.module and other files and saw a lot of references to ctools functions, but then got a little lost.

What and where is the function that handles that return value?

ADDITION/CORRECTION:

For Views in Drupal7, the cache is built up by Ctools and its _ctools_export_get_defaults() function that is defined in .../ctools/includes/export.inc.  It is called many ways down the line from views_get_all_views():

function views_get_all_views($reset = FALSE) {
  ctools_include('export');
  return ctools_export_crud_load_all('views_view', $reset);
}

where ctools_export_crud_load_all() eventually calls it.  The kicker for grep'ing around to find this is that it uses $function = $module . '_' . $export['default hook']; to cycle through all the modules that implement the hook, and that is defined in views.install:

'default hook' => 'views_default_views',

so it certainly took a bit to find but it is a nice api way to allow all sorts of modules to export objects in a defined fashion.  I won't include the code here as it's a bit more verbose than the D6 version below but do let me know if you need any other help on this.

MY BAD:  The following for D6....D7 answer above but I'll keep this in here if anyone in D6land ever needs an answer:

If what you are asking is where does Views build up its cache of default views, it does this via the _views_discover_default_views() function found in .../views/includes/cache.inc:

/**
 * Scan all modules for default views and rebuild the default views cache.
 *
 * @return An associative array of all known default views.
 */
function _views_discover_default_views($reset = FALSE) {
  static $cache = NULL;

  if (!isset($cache) || $reset) {
    $index = views_cache_get('views_default_views_index', TRUE);

    // Retrieve each cached default view
    if (!$reset && isset($index->data) && is_array($index->data)) {
      $cache = array();
      foreach ($index->data as $view_name) {
        $data = views_cache_get('views_default:' . $view_name, TRUE);
        if (isset($data->data) && is_object($data->data)) {
          $cache[$view_name] = $data->data;
        }
      }
    }
    // If missing index, rebuild the cache
    else {
      views_include_default_views();
      $cache = array();

      foreach (module_implements('views_default_views') as $module) {
        $results = call_user_func($module . "_views_default_views");
        if (!empty($results) && is_array($results)) {
          foreach($results as $name => $view) {
            // Only views with a sufficiently high api version are eligible.
            if (!empty($view->api_version) && $view->api_version >= 2) {
              // Do not cache dead handlers.
              $view->destroy();
              if (!isset($cache[$name])) {
                $cache[$name] = $view;
              }
              else {
                watchdog('view', "View name '@name' is already taken", array('@name' => $name), WATCHDOG_ERROR);
              }
            }
          }
        }
      }

      // Allow modules to modify default views before they are cached.
      drupal_alter('views_default_views', $cache);

      // Cache the index
      $index = array_keys($cache);
      views_cache_set('views_default_views_index', $index, TRUE);

      // Cache each view
      foreach ($cache as $name => $view) {
        views_cache_set('views_default:' . $name, $view, TRUE);
      }
    }
  }

  return $cache;
}


what json structure does simple oauth expect? Drupal 8.
I'm new with simple Oauth.
I had manage to do this:

But I want to do it with the Raw format, cuz my frontend is in Angular, so I will send a Json to Drupal.

This is my first try:

{
    "grant_type":"password",
    "client_id":"f011cc58-40ce-43a9-8f71-842494e3a997",
    "client_secret":"abc123",
    "username":"test",
    "password":"test"
}

And this is the response:

  {
      "error": "invalid_grant",
      "message": "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid,
  expired, revoked, does not match the redirection URI used in the
  authorization request, or was issued to another client.",
      "hint": "Check the configuration to see if the grant is enabled." }

I have set up the Content-type: Application/json but I got the same result.

Any idea??

It will depend if the backend can receive a JSON format.

In my case, I am working with the Drupal 8 Module simple Oauth. and the The format for OAuth 2.0 Bearer tokens is actually described in a separate spec, RFC 6750.

More concrete here

  The entity-body follows the encoding requirements of the
  "application/x-www-form-urlencoded" content-type as defined by HTML
  4.01 [W3C.REC-html401-19991224].

So, In my particular case, I will try to send a form-data from angular.


Twig overriding parent variables I want to override the block.html.twig 'classes' variable in my block--system-branding-block.html.twig which extends block.html.twig. I tried to set the 'classes' inside block--system-branding-block.html but this didn't work.

block.html.twig

{%
 set classes = [
  'block',
  'block-' ~ configuration.provider|clean_class,
  'block-' ~ plugin_id|clean_class,
]
%}

 {{ title_prefix }}
 {% if label %}

{{ label }}

 {% endif %}
 {{ title_suffix }}
 {% block content %}
   {{ content }}
 {% endblock %}

block--system-branding-block.html.twig

{% extends "block.html.twig" %}

{% block content %}
  {% if site_name %}

     <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}

  {% endif %}
  {% if site_slogan %}

{{ site_slogan }}

  {% endif %}
{% endblock %}

I want to put another entry in the classes variable just for the block--system-branding-block.html.twig witch extends the block.html.twig

It's not quite the approach you had in mind (modifying the classes variable) but I would recommend you do as Bartik does and work with the Attribute object instead:

{% extends "block.html.twig" %}

{% set attributes = attributes.addClass('new-class-goes-here') %}

{% block content %}
  {% if site_name %}

     <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}

  {% endif %}
  {% if site_slogan %}

{{ site_slogan }}

  {% endif %}
{% endblock %}

I think the key thing here is that the variable you are modifying is initialized (and used) outside of the twig block. If the variable were initialized inside the twig block then I can see needing to override it inside the child templates's twig block as well.

More on working with Attributes in templates here: https://www.drupal.org/node/2513632


Profile2 add fields as content type Is it possible to assign a content type to a field using profile2 module ? The website is developed in Drupal 7.

For example i have a content type product and another one images. I would like to have a profile which has as fields all the fields from product content type and also to be able to add more than 1 image content type to the same profile.

Please check out Entity Reference Module.
It might help.


Commerce Paypal Confirm Pane missing I have installed Drupal Commerce with latest version and also Commerce Paypal + Commerce Paypal Express Checkout.

EC is working so far, but I can´t find the Confirm-Pane on the checkout page/configuration.

Can somebody give me a tip what to do to make it visible on the checkout configuration.

It should be visible under "Confirm Order" and its called:
 "Express Checkout review and confirm (only to be used on the confirm order page)"

I fixed it...

I had a similar module installed (commerce_paypal_ec) and it was conflicting with commerce_paypal submodule for EC.

i misunderstood the concept, i tought i had to install submodules but those exist already in commerce_paypal.

in case somebody run into the same problem.

kind regards,
kevin


Configure page title block for contact form pages only I want the page title block to display on the contact form pages, because the nodes have their titles in their display.

It seems for a form you can't add the title to the form display, thus leaving me with the option to display it via the page title core block.

What I've tried as configuration for the block under visibility:

Contact form bundle: none selected (= for me, assuming: all)

Custom menu link bundle: Negate the condition (= for me, assuming: none)
Content type: Negate the condition (= for me, assuming: none)
Redirect type: Negate the condition (= for me, assuming: none)
All other configurations -> untouched (= for me, assuming: all)

But, the page title is never being displayed. Only when I deselect everything I see my page title... but I only need it on some pages.

Summarized, I want to only display the page title on specific pages, in a structural way (which means: no CSS hack)

You only need to select the Contact form bundles you want to display the page title on. Leave anything else untouched.


Number of paragraph items and translation I know that Paragraph field itself are not translatable for some reasons. I wanted to know if we could still have separate number of paragraph items between two translations of a node.

Example:

Node 1 FR

Paragraph 1
Paragraph 2

Node 1 EN

Paragraph 1
Paragraph 2
Paragraph 3

I found no clear explanations on that.

Not really in an easy way. We're working on an alternative approach to making the field translatable in the experimental paragraphs collection project: https://www.drupal.org/node/2846682.

Basically, this adds a setting to optionally control visibility of a paragraph in another language. This is a useful approach for use cases where differences between language are the exception and not the rule.

You can also build something similar yourself with a standard list field or an entity reference field to languages and then implement something in preprocess, twig or entity access to hide the paragraphs based on that.

But the only way to have completely different paragraph structures is to have the field translatable, and that's still a work in progress.


How to allow a role to block other users? Looks like there still isn't a great anti-spam solution for D7 ;-(

I already have flags for nodes and comments with automatic unpublish once enough users flag it.

I want to be able to give users of a certain role the permission to block other users and possibly unpublish any content of that user.

I don't see a permission for "block user". How can this be done?

Sounds like you must do it by custom module.

For blocking user, use db api and just change status column (users table) value to 0.

Similar things is for unpublish selected user content. All you need is in node table.

So you need two UPDATE statement for this job. That's all.

BTW. Do you try mollom for anti-spam? You can specify any form to work with mollom.
Maybe you can configure this module to work with logged in users.

Mollom has nice permission, e.g.: Bypass Mollom protection on forms, so you can choose which role may bypass spam checking or not. Then just try to find any hook declared by Mollom module that allow you to block user when spam is detected.


problem merging views row-data into Drupal.settings I have a custom view and a custom row template.
For each row, the template defines a variable $rowdata.  For example:

> row #0:  $rowdata = array(0=>array('a','b'), 1=>array('a','c'))
> row #1:  $rowdata = array(0=>array('a','b'), 1=>array('a','d'))
> row #2:  $rowdata = array(0=>array('x'), 1=>array('x'))

What I Am Trying To Accomplish

I want merge the rowdata from all the rows:

   $merged_rowdata = array(
      0=>array('a','b'),
      1=>array('a','c'),
      2=>array('a','b'),
      3=>array('a','d'),
      4=>array('x'),
      5=>array('x')
    )

and store the result in Drupal.settings.mymodule.$viewID.merged_rowdata:

Drupal.settings.mymodule.$viewID.merged_rowdata = array(
  0=>array('a','b'),
  1=>array('a','c'),
  2=>array('a','b'),
  3=>array('a','d'),
  4=>array('x'),
  5=>array('x')
)

(Note:  All rows have the same value for $viewID)

What I Tried

I tried placing the following code in my row template:

drupal_add_js(array('mymodule' => array($viewID => array('merged_rowdata' => $rowdata))), 'setting');

But this does not merge the rowdata in the way that I want, as described above.  Instead, it replaces $viewID with the row_index:

Drupal.settings.mymodule = array(
  0 => array('merged_rowdata'=>array(0=>array('a','b'), 1=>array('a','c'))),
  1 => array('merged_rowdata'=>array(0=>array('a','b'), 1=>array('a','d'))),
  2 => array('merged_rowdata'=>array(0=>array('x'), 1=>array('x')))
)

I found that if I replace the variable $viewID with a string literal, eg 'myview':

drupal_add_js(array('mymodule' => array('myview' => array('merged_rowdata' => $rowdata))), 'setting');

then the rowdata gets merged in the way that I want:

Drupal.settings.mymodule.myview.merged_rowdata = array(
  0=>array('a','b'),
  1=>array('a','c'),
  2=>array('a','b'),
  3=>array('a','d'),
  4=>array('x'),
  5=>array('x')
)

Anyone know how I can get my desired result?  Is there some way to "tell" drupal_add_js that the variable $viewID has the same value for all the rows?

Background

My style template loops through each row of the view output, and executes the row template on each row.  Here is the code for my style template:

<?php foreach ($rows as $id => $row): ?>
  <div>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

If the string literal is giving you what you want, I'd try this:

drupal_add_js(array('o4mmgal' => array($view->name => array('merged_rowdata' => $rowdata))), 'setting');


Composer update : Package "drupal/module_name" listed for update is not installed. Ignoring After hours of struggling to update Drupal with Composer (see my solution here), I have now some difficulties to update some modules. I was able to update with composer update drupal/bootstrap:3.11 --with-dependencies, but I could not update a module with composer update drupal/pathauto:1.1 --with-dependencies, which returns the following error.

  Package "drupal/pathauto:1.1" listed for update is not installed.
  Ignoring.
  Nothing to install or update.

The content of the composer.json file is the following.

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "^1.4",
        "drupal/views_slideshow": "^4.6",
        "drupal/metatag": "^1.4",
        "drush/drush": "dev-master",
        "drupal/core": "~8.5",
        "drupal/pathauto": "1.1",
        "drupal/bootstrap": "3.11",
        "drupal/token": "1.1"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": [
          "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
        ],
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ]
}

I tried with composer update drupal/token, but it gives the following error.

  Nothing to install or update

composer install drupal/token gives the following error.

  Invalid argument drupal/token.
  Use "composer require drupal/token" instead to add packages to your composer.json.

Instead, composer require drupal/token gives this error

  Using version ^1.1 for drupal/token
  ./composer.json has been updated
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Nothing to install or update

I checked the composer.lock file and its content is the following.

    "name": "drupal/token",
    "version": "1.1.0",
    "source": {
        "type": "git",
        "url": "https://git.drupal.org/project/token",
        "reference": "8.x-1.1"
    },

So, it seems thats it is correct, but the module page still shows it as requiring to be updated.

How can I solve this and install these modules?

I found what was the issue in my case. I post my solution. Even if it is specific to my issue, maybe it could help other users.

I didn’t install these  Drupal 8 modules. The developer who installed them used Drush (he should have used Composer). So I had the same modules installed twice, in /module and in modules/contrib I’ve deleted modules previously installed with drush  in /module and run composer update. That fixed the problem.


How to migrate a book from Drupal 6 to a menu in Drupal 7 Recently I came across a situation where I had to migrate a book with lots of links into a menu (since the customer wanted a simple navigational menu).

I came up with some code that worked pretty fine, so I decided to share it as an answer.

If you believe it could have been done in a better way, please feel free to comment and propose your ideas and methods. This code requires you to be somewhat familiar with the Migration process and the Migrate module.

To begin with we define a class derived from Migration.

<?php

/**
 * To define a migration process from a set of source data to a particular
 * kind of Drupal object (for example, a specific node type), you define
 * a class derived from Migration. You must define a constructor to initialize
 * your migration object. By default, your class name will be the "machine name"
 * of the migration, by which you refer to it. Note that the machine name is
 * case-sensitive.
 *
 * In any serious migration project, you will find there are some options
 * which are common to the individual migrations you're implementing. You can
 * define an abstract intermediate class derived from Migration, then derive your
 * individual migrations from that, to share settings, utility functions, etc.
 */
abstract class MenuMigration extends DynamicMigration {

public function __construct() {

# Always call the parent constructor first for basic setup.

parent::__construct(MigrateGroup::getInstance('Menu'));

}
}

We now create a class that extends the above.

class EducationalGuideMigration extends MenuMigration {

public function __construct() {

parent::__construct();

#Define variable for the default user id (user="grammateia") wherever it is used (uid, revision_uid, etc.).
$user=36;

# Human-friendly description of your migration process. Be as detailed as you like.

$this->description = t('Migrate the "Studies Guide" menu');

We create the mapping in the database and our query.

$this->map = new MigrateSQLMap($this->machineName,
    array(
      'mlid' => array('type' => 'int',
                       'not null' => TRUE,
                       'description' => 'Menu link ID',
                       'alias' => 'ml'
                      )
    ),
    MigrateDestinationMenuLinks::getKeySchema());

$query = Database::getConnection('default', 'migrationDB')
           ->select('book', 'b');
$query->leftJoin('menu_links', 'ml', 'ml.mlid = b.mlid');
$query->fields('b', array('nid', 'mlid'))
        ->fields('ml', array('menu_name','mlid', 'plid', 'link_path', 'router_path', 'link_title','options', 'module', 'hidden', 'external', 'has_children', 'expanded', 'weight', 'depth','customized', 'p1', 'p2','p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'updated'))
        ->condition('bid', 30, '=')
        ->orderBy('ml.mlid');

As you can see we create our mapping based on the mlid (menu link id) primary key. You can find this key in the menu_links table and the book table. The book table holds only keys, namely nid, mlid and nid. The menu_links table holds all the info pertaining any sort of navigation menu in your drupal site, from your custom menus to administrative ones.

Luckily, Migrate provides us with a migration class for our mapping called "MigrateDestinationMenuLinks".

We use left join to join the two tables mentioned above. Obviously we need to know from which book we have to get our data so the book with id=30 is the one I was interested in.

We then execute the query and provide the destination menu plus anything we won't migrate (these unmigrated fields get default values).

# Create a MigrateSource object, which manages retrieving the input data.
$this->source = new MigrateSourceSQL($query);

# Set up our destination menu
$this->destination = new MigrateDestinationMenuLinks();

/**
 * SOURCE FIELDS NOT TO BE MIGRATED
 */

$this->addUnmigratedSources(array ('module', 'options', 'has_children', 'depth','hidden', 'updated', 'external', 'customized', 'expanded', 'link_path', 'router_path', 'mlid', 'menu_name', 'mlid'));

    /**
 * DESTINATION FIELDS NOT TO BE MIGRATED
 */

$this->addUnmigratedDestinations (array('module', 'options', 'has_children', 'depth','hidden', 'updated'));

Now it's time to map the fields that we do need to migrate.

  /**
 * FIELDS TO BE MIGRATED
 */

$this->addFieldMapping('menu_name')
        ->defaultValue("menu-studiesguide");
$this->addFieldMapping('plid', 'plid')->sourceMigration($this->getMachineName());
$this->addFieldMapping('link_path', 'link_path');
$this->addFieldMapping('router_path')->defaultValue('node/%');
$this->addFieldMapping('link_title', 'link_title');
$this->addFieldMapping('external')->defaultValue('0');
$this->addFieldMapping('expanded')->defaultValue('0');
$this->addFieldMapping('weight', 'weight');
$this->addFieldMapping('customized')->defaultValue('1');
$this->addFieldMapping('p1', 'p1')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p2', 'p2')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p3', 'p3')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p4', 'p4')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p5', 'p5')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p6', 'p6')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p7', 'p7')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p8', 'p8')->sourceMigration($this->getMachineName());
$this->addFieldMapping('p9', 'p9')->sourceMigration($this->getMachineName());

In the menu name mapping we provide as a default value, our menu's machine name. (whatever name you gave is appended with the "menu-" prefix by Drupal).

Now you will notice that for the fields plid and p1 to p9 I have added this argument:

->sourceMigration($this->getMachineName());

First of all plid and p1 to p9 are all menu link ids. Plid is the immediate parent of every mlid and p1 to p9 is essentially our navigation menu for every menu branch.

What the argument does is pretty simple. It prety much tells our migration, "You know what, I got all the mlids from the query so any parent id you create is gonna be one of those menu link ids". (Note: that is why in our query we order by mlid).

So now ok, we have our menu, however the menu items are supposed to have links that correspond to nodes right? Well the book I had to migrate had 2 different content types which I also migrated, but their nodes were not assigned to these menu links. Also the nids I can get from the Drupal 6 are not the ones I need to assign to my menu links. So what do we do? Enter prepareRow().

function prepareRow($row) {

    $current_nid=$row->nid;

    $querymmi = Database::getConnection('default')
            ->select('migrate_map_idrimata', 'mmi');
    $querymmi->fields('mmi', array('destid1', 'sourceid1'))
            ->condition('sourceid1', $current_nid, '=');

    $resultmmi = $querymmi->execute();

    if($resultmmi->rowCount()==0){

        $querymms = Database::getConnection('default')
            ->select('migrate_map_studies', 'mms');
        $querymms->fields('mms', array('destid1', 'sourceid1'))
            ->condition('sourceid1', $current_nid, '=');

        $resultmms = $querymms->execute();

        if($resultmms->rowCount()==0){
            print "EVALA TH XAROULA EDW \n";
            print "path: node/9118 \n";
            $row->link_path = "node/9118";
        }

        else{
            print "STUDIES PATH INSERTED SUCCESFULLY \n";
            $row->link_path = "node/" . $resultmms->fetchField(0);
        }
    }

    else{
        print "IDRIMATA PATH INSERTED SUCCESFULLY \n";
        $row->link_path = "node/" . $resultmmi->fetchField(0);
    }
   }

So what we do here is this. Every time you migrate nodes a migrate map is created that corresponds drupal 6 nids to Drupal 7 ones. So we query those tables (as I mentioned earlier my book had 2 different content types) and we compare every nid we get from this migration's query with the source nids from our map tables.

We use this "if" condition to handle any case where no results are returned in our comparison:

if($your_result_variable_here->rowCount()==0)

The first condition checks if we have nids from our first map table, if not go check the other one.
The second does the same check, but the reason to actually have it there is to provide a default value to a menu link if our condition doesn't return true (highly unlikely but it happens).

And finally how do we provide the correct nid to our menu link? Well be it either a default value or one of the node ids this is what we do:

$row->link_path = "node/" . $resultmms->fetchField(0);

Get the link_path field from every row of our query, concatenate the string "node/" with the nid that we get from our result set. The fetchField(array index # here) does that.

So that was it. Hope my explanation was clear enough and it actually helps out.


Content type permissions are not working I'm trying to give users permission to edit certain content types, but it's not working. I'm having trouble tracking down which module could be the culprit. (I've used a couple of beta modules)

How should I go about tracking down this problem?

make sure you have proper permissions assigned.Try rebuilding the site permissions.

If it still does not work try disabling individual permission based modules and rebuild site permission each time you do so and check.

You can also try using the devel node access module which gives a block which is placed below each content.


A whole view disappears I have deployed user generated views to a production site using Views (6.x-2.12) bulk export feature; that is, views are saved in the code as mymodule.module and mymodule.views_default.inc, the latter of which contains 12 views in more than 11,000 lines.

Sometimes, one or more views suddenly disappear from the site. Flushing all caches usually fixes it, but it is hard to duplicate the issue and it bothers me that it may happen again in the worst time.

Possible causes that I think of are:

Does the .inc file have too many lines (> 11K)?
I have saved the .inc file with Windows new lines, while the server is Linux.

Could one of these be the cause?
Anyone experienced a similar issue?

Solution for the "to many lines" problem:

function YOURMODULE_views_default_views() {
    $files = file_scan_directory((drupal_get_path('module','YOURMODULE').'/views','.view'));
    foreach($files as $absolute => $file) {
        require $absolute;
        if(isset($view)) {
            $views[$view->name] = $view;
        }
    }
    return $views;
}

This way every view-code can be stored in it's own file inside a views subfolder inside YOURMODULE as some_name.view.


Cannot figure out where the tmp folder is to add the .htaccess file per http://drupal.org/SA-CORE-2013-003 That doesn't make any sense to me. I do not have a tmp folder anywhere outside the root. I cannot find the /tmp folder supposedly outside the folder where my Drupal instance is located. Well, let me correct that. I found one, but placing the recommended .htaccess file in it didn't solve the error message. It didn't seem to be the correct tmp directory. Maybe I don't fully understand where outside the root dir is at? Isn't it the directory above where the installation is at? Is it in the html folder, the sites folder, or above the html folder?

Will the instructions in http://drupal.org/SA-CORE-2013-003 work if I create a tmp folder in the html folder? Where exactly do I create the tmp directory?

Maybe I don't fully understand where outside the root dir is at? Isn't it the directory above where the installation is at?  Is it in the html folder, the sites folder, or above the html folder?

The tmp folder is where your configuration says it is.

I looks like you've already navigated to Administration » Configuration » Media  » File system, and found that the field "Temporary directory" says /tmp - so that is where it is (this is also the default location).

Now, this is a file system path, not a Drupal path.  The "/" in front tells you it is in the file system root.

To navigate to it, use the following command in the Gnu/Linux CLI:

 cd /tmp

  Will the instructions in http://drupal.org/SA-CORE-2013-003 work if I create a tmp folder in the html folder?

No.

  Where exactly do I create the tmp directory?

You don't create it.  It should already exist on your system.

To fix the error message regarding the .htaccess in /tmp related to the security update you mention, do as follows:

First, in the GNU/Linux CLI, use the following two commands:

 cd /tmp
 rm .htaccess

Then in the Drupal GUI, as admin, navigate to Administration » Configuration » Media  » File system.  Do not change anything, but press "Save configuration".  This will make Drupal create the correct .htaccess in the right place.


Debugging Migrate: how to print what data's mapped to a field I have a migration module that imports data from a CSV. I've steadily been adding code to the module and fields to the CSV, and it's always worked, albeit sometimes only after some work. But now there's one profile2 profile among the many I'm importing to in which the text fields don't get any data successfully imported to them. This happens even when I just put '1' or '0' for them in the CSV. Oddly, the non-text fields in the profile2 profile import fine, even though they're later in the CSV and the module code.

My question is how I go about debugging this. I couldn't find a 'how to debug Migrate' page in the documentation or on the web. I've found Migration::displayMessage, but what can I print via this to show what data's been mapped to these fields from the CSV? I just get the abstract mapping structure without any data from my CSV when I run Migration::displayMessage('<pre>'.print_r($this, TRUE).'</pre>', 'debug');

Answer from Mike Ryan: I usually run migrations in drush and, when not stepping through in a
debugger, use drush_print_r(). The key points you want to instrument are
prepareRow() (dump $row to make sure the source data is being pulled
correctly in the first place) and prepare() (dump $node to make sure the
source values are getting properly mapped into the node object that's about
to be saved).


How to create a form, using a function, located inside a class Usually when we need to create a form we create a function inside module and call:

$form = drupal_get_form('function_name');
drupal_render($form);

Now I started using entities and created a subclass of EntityDefaultUIController. With a form generating function:

class transactionUIController extends EntityDefaultUIController {
  public function overviewForm($form, &$form_state) {
     //blah blah
     return $form;
  }
}

I need to get this from in an external module. What should I pass to drupal_get_form function?

You can use the form callbacks provided by the entity module. So for your example (assuming your entity_type is named 'transaction') you would call drupal_get_form like so:

drupal_get_form('entity_ui_overview_form', 'transaction');

You can find other Entity UI form related functions here.


Display set of Views rows with different view modes I have a Drupal 8 View with a set of rows, which are each rendered as a compact list teaser. Additionally I need to display those rows inside the same view in a another view mode (e.g. "grid teaser" with an extra image). As a result the visitor should be able to switch between the different view modes by toggling the display.

The template views-view.html.twig should contain this:

  {{ rows }}

  {{ rows_grid }}

I don't really know how to render those additional rows. I thought about using the hook template_preprocess_views_view:

function template_preprocess_views_view(&$variables) {

  // collect node ids
  $nids_rows = array();
  foreach ($variables['view']->result as $row){
    $nids_rows[] = $row->nid;
  }

  // load nodes
  $nodes_rows = Node::loadMultiple($nids_rows);

  if(!empty($nodes_rows)){
    // get views of nodes as grid
    $variables['rows_grid'][] = node_view_multiple($nodes_rows, 'grid');
  }
}

But the resulting render array is not in the same form like $variables['rows'] and I'm not able to loop through those rows_grid to wrap them with specific html (like in views-view-unformatted.html.twig).

Is there a function like view_load_rows($nids, $view_mode)? Or is there a way to alter the render array with some additional keys like '#theme' to get a real rows render array?

Maybe there is even an much simpler way to accomplish this. Any Ideas?

You can add another view display and put it below the main view output using block or view attachment.


Hide Authoring info on certain pages/nodes I am looking for a way to hide the "Submitted By: .... on ...." info on certain pages. I am aware that it can be removed from all pages of the 'Basic Page' or 'Article' type through the configuration settings, however I would like the info to appear on all pages unless I turn on a setting whilst creating/editing the page which hides it on that certain page.
Does anyone know of a way to do this?
Thanks,

You could add a checkbox field to the content type, and adjust the node.tpl file. If the box is not checked, don't print submitted by.

Add the field to all content types (sounds like thats what you asked for) and remove it from each display under "Manage Display".

Then, in template.php, implement template_preprocess_node:

mythemename_preprocess_node(&$variables) {
  $node = $variables['node'];

  // here we are creating a brand new variable
  // true, unless otherwise set by editors
  $variables['show_authoring'] = TRUE;

  // the field exists on the node object
  // update our custom variable to this field value
  if (isset($node->field_show_authoring)) {
    $variables['show_authoring'] = $node->field_show_authoring[LANGUAGE_NONE][0]['value'];
  }
}

If you want all nodes have this, you can copy in node.tpl.php to your theme or edit the one in your theme if it exists, and do:

<?php if ($display_submitted && $show_authoring): ?>
  <div class="submitted">
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

You could remove $display_submitted if you wanted to, I left that there in case you wanted control in the future to completely disable showing authoring for certain content types, like Webform for example. My syntax should be correct but I did not have a chance to test this in a sandbox.

See more:

template_preprocess_node
How do I create a variable for my template file?
Preprocessing function for node.tpl.php


Show 'log in' in user menu when not logged in I'm asking myself, where is the code that hides "My account" & "Log out" in the user menu? Just curious, to learn from that code. Any way to know where to search if you want to know something like this?

I added a "Log in" link to this menu, and I want to hide this when nobody is logged in.

You can add a menu link to user/login, the access callback of that verifies that it is only shown to anonymous users. Just like user/logout is only visible for logged in users.

The definition of these callbacks() are, as mentioned in the other answer, in user_menu()


How to prevent users with negative balance of user points from viewing nodes? I have a rule that deducts 1 point from users viewing a node, however the problem is that users with a negative balance can still view a node. So I would want to prevent this.

I'm using Drupal 7 with modules Rules and User Points.

Any suggestions?

Your question actually contains 2 challenges:

Which Rules Event to use?
Check the current balance of user points of the user?

Read on for an answer to address each of those challenges.

1. Rules Event to use

If you'd use Rules event node_view, then you're too late, because the node is already being viewed (which is exactly what you want to prevent). Instead you need to use (System) event "Drupal is initializing" (= init), which is actually BEFORE the node is actually being viewed.

2. Check current balance of user points

However, you also want to disallow viewing nodes for users who have a negative user points balance. The challenge with that is that there is no out-of-the-box Rules Condition to check that balance.

Have a look at this Rules example (in Rules export format):

{ "rules_stop_node_access_for_user_with_negative_points" : {
    "LABEL" : "Disallow node/* access for a user with negative points",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "0" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have insufficient points (you only have [total-points:value] points ...)." } },
              { "redirect" : { "url" : "no_access" } }
            ]
          }
        ]
      }
    ]
  }
}

The Rules Condition added here, is to only perform the Rules Action for attempts to browse a path like node/* (adapt to what fits for your case).

This rule retrieves, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If it is negative, it will display an appropriate message starting with "You have insufficient points ...", and it redirects to a relative path like no_access (adapt to what fits for it).

This rule uses the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module.

The clue to make this rule work is the very first Rules Action "Load user points of a user". Refer to my answer to "How to access current amount of earned userpoints in a Rules Condition?" for more details on this.


Error after installing module twice: Configuration object already exist I've followed How to create views programmatically in Drupal 8, but as I asked in this topic, my view doesn't appear in my list.

When I install my module twice (Enable -> Uninstall -> Enable), I have an error:

  Configuration object views.views.viewsname already exist

I also tried to import it directly in Drupal, copied the exact same code and this worked.

As the error says, the problem isn't with your module, but simply that the configuration your module is trying to create already exists in your installation.

You have two options to get it installed:

delete the configuration first, in the UI or programatically (How do I remove a configuration object from the active configuration?) and then add an enforced dependendency on your module, to make sure it is removed when your module is uninstalled. Note that you must first remove the config, the enforced dependency that removes your config only works once installed using the new definition.
Provide as optional config in config/optional instead of config/install. Optional config is different from other config in two ways:

First, it is only installed when all the required dependencies exist. That is useful if you have optional integration with another module and if it is installed, provide some configuration for it. This even works if that other module is installed later on. Configuration with missing dependencies in config/install fails with an error as Drupal assumes your module will not work correctly if the config can not be installed.
Second, it will also be silently skipped if the config exists already, which is the relevant thing for your case. It will however also be silently skipped if the existing config just happens to be a view with the same name that is actually something else.


Classification: {{ content.field_classification.value }} not displaying Hoping someone can assist me please.

I am trying to display the value of a custom field in a bootstrap sub theme

I have created my node--testtype.html.twig template and that seems to work.

I'm trying to just show the content of one field, the machine name is field_classification.

When I use
Classification: {{ content.field_classification.value }}
 the Classification displays as expected, but the value of my field_classification doesn't.

Can anyone see what I am doing wrong please as thought I d copied the correct code from what I have read?

{{ content }} is a render array and does not have a .value, just use {{ content.field_name }}

You only need the .value when you want to print the raw values of an entity object like node, e.g. {{ node.field_my_integer.value }}


Does the 'field table' always hold the current value? Or is it only in newest revision? As I understand it, the current value for every field can be found in corresponding data table (e. g. field_data_body) and the history of its changes in corresponding revision table (field_revision_body) with the value of newest revision being the same as the value in data table.

Is that, however, really true or do I have to (to get the current value) look into the newest revision (which id can be obtained from 'entity type' table (e. g. node table)). If that's the case then does the data table hold the first value or what?

In other words, when dealing with content in Drupal 7 directly (accessing database and not using Drupal functions (load_entity, etc.)) is it safe to work only with 'data' tables and not caring about 'revision' ones?

//I'm almost sure the way I understand is right and everything seems to verify it, I'd still like to be totally sure.

You are totally correct, the newest value is in the field_data table, you can rely on that.

field_revision just has a copy of the same data so that it knows about the revision immediately. I think it's just more hassle free to keep field_revision completely up to date rather than being one step behind field_data.


How to translate Global:PHP in the view? I need translate view's global:php in the no results behaviour,Can i do that?

Try by using your text inside t().

t('your text to display'); or t($string);


link a calendar to another content type I have a calendar in Drupal 7, and I want to link this calendar with other nodes.

How do I do this? Which module should I use?

I am using Drupal 7.

You need to add a "date field" to the test content type.

And with views +date field + calendar you will be able to do it.


Exclude a not-hidden field in the content In Drupal 7, I'm tying to show all the taxonomy terms from a specific vocabulary linked to the current node being viewed. I'm doing this with a new block defined in my module.

I added a field called tags in my contenttype and gave this field the whole taxanomy behavior. This made it possible to get the terms with:

$node = menu_get_object();
$node->field_tags <- array of tags to use

But, here comes the problem, this field is only there when it's set to visible in admin/structure/types/manage/page/display . But when i do that it also becomes visible in the content. If i put it to hidden it does not only get removed in the content/node view, but it's also gone from the whole $node object.

It there a way of getting the fields from the current node that are set to hidden?

Thanks,
Jonathan

The field shouldn't be removed from the $node object...if it is then I'd check what custom/contrib modules you have installed that might be causing this to happen. It's not supposed to.

A sure-fire way to make sure all fields are attached to the object is to re-load it:

$node = node_load($node->nid, NULL, TRUE);

That will re-load the $node fresh from the database, with all fields attached. You do take a performance hit doing this. However, Drupal core will never have removed the field from the $node object in the first place, so if you've got some other theme/module that's doing this you'll either have to find/repair/remove it, or use a more a extreme method like the one above.


Programatically upload/link images and attatch to Ubercart's product node? One of the things my Ubercart module needs to be able to do is programatically upload or link (this being preferred as it means I don't have to mirror it) an image and attach to Ubercart's product node. The user will give me some information, and my module will fill in the name, description, and product image. The product image is a big hurdle which I have no idea how to conquer.

The core Ubercart module product has a dependency on Drupal's core Image module, which is where I'm assuming is handling all the images. I thought I could learn how to do it by looking at the product module's code, but I'm having trouble wading through and understanding the thousands of lines of code. I'm not even sure of any other module that does something similar to what I'm doing, so I'm out of example code.

Does anyone know of a way to accomplish what I'm wanting to accomplish?

Ubercart already has the option of a predefined cck imagedfield, where do you plan on getting the correct image programatically? I remember using a default imagefield image before in the field settings.

Have a search for creating ubercart products programatically, its a fairly common thing as people import products from other dbs and excel files etc.

Here is a start, it all depends on where your data is coming from;

<?php
function MYMODULE_createnode() {

global $user;
if (isset(

$_POST['values_from_form']))
  {
    $values['nid'] = intval(check_plain($_POST['nid']));
    $values['title'] = check_plain($_POST['title']);
    $values['type'] = 'product'; //uc node content type
    $values['body'] = $_POST['body'];
    $values['name'] = $user->name;
    $values['uid'] = $user->uid;
    $values['field_cck_field'][0]['value'] = $_POST['cck_field']; // Custom CCK field example for whatever it was you were wanting to do
    $values['status'] = 1;

    $node = node_submit($values);

    node_save($node);

    }
}
?>


"CSRF validation failed" when try to send POST request in custom module This is my full codes. I want to create a node with service post method. But I cant post. "CSRF validation failed".

I followed this tutorial: https://www.youtube.com/watch?v=Wz2uaRF9RGc

Anyone suggest something.

<?php
/**
* Block Info
*/
function mymodule_block_info(){
$blocks['mymodule_testing'] = array('info' => t('Mips Testing Block'));
return $blocks;
}

function mymodule_block_view($delta = ''){
$blocks['content'] = '
MIPS Testing Block
';

/* POST Request */
$post_data_results = mymodule_create_requested_data();

return $blocks;
}

/* Create data with POST Method */
function mymodule_create_requested_data(){
$path = $_SERVER['HTTP_REFERER'] . 'serve/node';

$node_type = 'apply';
$node_title = 'This is title ' . date('c');
$node_body = 'Node Body';
$node_format = 'filtered_html';

$node_data = '{
    "type": "'. $node_type .'",
    "title": "'. $node_title .'",
    "body": {
        "und": {
            "0": {
                "value": "'. $node_body .'",
                "format": "'. $node_format .'"
            }
        }
    }
}';

$node_options = array(
    'headers' => array(
        'Content-Type' => 'application/json',
        'Cookie' => mymodule_application_authentication('test', '123'),
        ),
    'method' => 'POST',
    'data' => $node_data
);

return drupal_http_request($path, $node_options);
}

function mymodule_application_authentication($username, $password){

if(isset($_COOKIE['mymodule_authentication_name']) && isset($_COOKIE['mymodule_authentication_id'])){
    return '' . $_COOKIE['mymodule_authentication_name'] . '=' . $_COOKIE['mymodule_authentication_id'];
} else {
    $login_url = $_SERVER['HTTP_REFERER'] . 'serve/user/login';

    $user_data = '{
        "username" : "'. $username .'",
        "password" : "'. $password .'"
    }';

    $user_options = array(
        'headers' => array('Content-Type' => 'application/json'),
        'method' => 'POST',
        'data' => $user_data
    );

    $result = drupal_http_request($login_url, $user_options);
    if($result->code == '200'){
        $user_data = json_decode($result->data);

        setcookie('mymodule_authentication_name', $user_data->session_name);
        setcookie('mymodule_authentication_id', $user_data->sessid);

        return '' . $user_data->session_name . "=" . $user_data->sessid .'';
    } else return FALSE;
}

}

You need to get a CSRF token before making your POST call.

function getCsrfToken(callback) {
  jQuery
    .get(Drupal.url('rest/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

and use this in your ajax call as a new header:

  jQuery.ajax({
    url: 'http://example.com/entity/node?_format=hal_json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken
    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });

https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities


Most viewed count always zero I try to adapt my Views block, I add Node Statistics: total views
but it always show Zero, what am I doing wrong? sth is missing

Verify if you have enabled “Count content views” within Statistics module configuration.
(admin/config/system/statistics for D7)


How to disable/turn off Automatic URL alias Could anyone suggest how to disable/turn off automatic URL aliases?

Automatic URL aliasing? It will be the Pathauto module doing that. You can disable it, but you will need to delete your current aliases as well, which the Pathauto module provides an interface for if you check its settings.


db_query group by to array I have the following query:

$query = "SELECT *
      FROM mytable
      {$typeClause}
      HAVING distance <= {$radius}
      ORDER BY distance ASC"
      GROUP BY type;

    $result = db_query($query);
    $points = array();

    while(($point = $result->fetchAssoc()) != null){
    }

In my db there is field 'type' which is a number
How can I get all records as an array without using the while statement above (something like fetchByGroup):

array(
        '1' => array( [all records of type=1] ),
        '2' => array( [all records of type=2] ),
        ......................................
    );

You cannot do this using native Drupal 7 functionality. You need to do that grouping in PHP. You should be using a foreach, not a while loop :)

  The most common case is to iterate over the result set with a
  foreach() loop.

Source: https://drupal.org/node/1251174


Difference between hook_page_alter and preprocess_page? I don't completely understand when I should use hook_page_alter(&$page) or template_preprocess_page(&$vars, $hook) in Drupal 7.

What is the best practices about that to use in template.php?

Thanks

The difference is their purpose.

hook_page_build() and hook_page_alter() are used to remove, alter, or add elements at the page level.
The $page array passed to hook_page_alter() contains the top level elements for each block region. By default they are the following ones:

page_top
header
sidebar_first
content
sidebar_second
page_bottom

An example of implementation could be the following one:

function mymodule_page_alter(&$page) {
  // Add help text to the user login block.
  $page['sidebar_first']['user_login']['help'] = array(
    '#weight' => -10,
    '#markup' => t('To post comments or add new content, you first have to log in.'),
  );
}

The preprocess functions are called to alter the variables that are passed to the template file. They cannot change the structure of the page, but they can alter the content of some elements of the page changing the content of those variables.
For example, the Overlay module removes the primary tabs when the page being visualized is the overlay.

function overlay_preprocess_page(&$variables) {
  if (overlay_get_mode() == 'child') {
    unset($variables['tabs']['#primary']);
  }
}


drupal site is really slow on VPS server I have a drupal 7 website on a VPS server with the following specifications:

Processor Name: Intel(R) Xeon(R) CPU E31270 @ 3.40GHz

Processor Speed (MHz):  3392.294

Total Memory:   3924628 kB

Free Memory:    276096 kB

Total Swap Memory:  4063228 kB

Free Swap Memory:   3894104 kB

Apache 2.2.29:  Running

DirectAdmin 1.47.0: Running

Exim 4.84:  Running

MySQL 5.5.31:   Running

Named 9.8.2rc1: Running

ProFTPd 1.3.5:  Running

sshd:   Running

dovecot 2.2.16: Running

Php 5.3.29: Installed

With one GB of ram, I thought that the slowness of my website might be because of the heaviness of tables. (Number of tables: 381, DB size: 60 MB)
But by searching the net, I found that my DB is not that heavy. I also noticed that in my services, the memory usage of httpd is 650 MB. I think this also might have something to do with slowness of my website.
Can anybody help me with this issue?
Thanks.

Isn't it closer to 4Gb RAM based on your posted stats?
A server with only 1Gb RAM will most likely not work properly with a full application stack. Apache and MySQL require memory to be performant. The least I'd recommend based on personal experience is 2Gb RAM.

What you can also do is perform traces on your site with xhprof to see what the slowest items are, and improve those.
APC and memcache can also help to boost speed. Or if you only have anonymous users, using the boost module can be a very quick fix, although it's not maintained actively anymore for Drupal 6 it seems.


How can I organize my content using hierarchical taxonomy? My question is rather simple, but I don't know how to do it ?

I want to display a content with various fields, but I want the user to browse "hierarchically". For instance :

Choose brand : BMW
Choose model : BMW / Z3
Choose specific model : BMW / Z3 / 2.0 i

I already made a taxonomy "Brand", a taxonomy "Model", I have a view that shows all brands.

What can I do ?

Thanks for advice, it would help me a lot !

I had a similar implementation on a drupal 6 site using Hierarchical Select. The drupal 7 branch turned out to be working slightly differently when I first tried to make the move.

There is also Simple hierarchical select which was probably developed because of these 'differences' between d6 and d7:

  "This module has been inspired by Hierarchical select but is much simpler (…)."

I haven't tried 'Simple hierarchical select' yet, but if I would re-build that d6 site again, I would probably go for 'Simple hierarchical select'.

Both let you generate a taxonomy tree with dependend parent-child-relationships. So instead of having one taxonomy brandand one one taxonomy model you would have a taxonomy tree taht would contain all the branches down to specific model.

In my case is was venues which then also contained the upper branches like cityand country.

PS: You could however also use entity references to build complex hierarchical content trees. You would then for example have a content type brand and a content type model referencing each other.  Nowadays I find this approach more convenient than dealing with taxonomy trees – but that's of course depending on personal preferences and/or content structure.