Must new tables be created in hook_update_N()? When you create a new table in hook_schema(), should that table be added in a hook_update_N() as well? Or is there some trick, or something I missed, to have databae-updates automatically add tables?

The documentation of hook_update_N() does not explain anything about introducing new tables, whereas the documentation of hook_schema() says:

  The tables declared by this hook will be automatically created when the module is first enabled, and removed when the module is uninstalled.

(Highlight is mine)

And if so, how to best avoid duplicating the schema definitions for the new table in both hook_update_N() and hook_schema(). Simply referring to the schema as follows:

 function hook_update_N(&$sandbox) {
   $schema = hook_schema();
   $name = "foo";
   $table = $schema["foo"];
   db_create_table($name, $table);
 }

Seems to work, but on changing the table again, will fail if a user runs the updates and gets to run two or more hook_update_N()s. After all: the first hook_update_N will then already install the correct database and the second hook_update_M() will try to add/change/alter columns that were already up-to-date.

How do you deal with this?

So just a copy paste from drupal.org. You also need to add the schema definition to hook_schema.

/**
 * Create new database table {mytable2}.
 */
function mymodule_update_7101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  db_create_table('mytable2', $schema['mytable2']);
}


View is removing iframe from custom text I'm using a global custom text field within a view that is meant to display an embedded youtube video.

However in the actual render of the view it's completely removed from the dom.

My first assumption was that ckeditor was not allowing the iframe tag and removing it itself. However I have it setup to allow iframe tags, and if I go back and edit the Global Custom text it still appears. If it didn't allow it I'm assuming it would not appear in the editor the next time I open and edit the field.

Also I'm able to embed iframes in the body text of nodes just fine. It's specifically in views.

I also attempted creating iframes with different src's in different divs but I still had the same behavior.

Are there other possible causes of Drupal removing iframes from custom text in views? Is this the expected behavior? If this is the expected behavior is there away around this?

EDIT: Forgot to mention that 'Strip HTML tags' is also turned off.

This is not the expected behavior of drupal views, Drupal Views usually not doing this.
I have done this before, and global text with iframe is working with no issue.
Maybe you have another issue like some javascript issue to prevent the load iframe form another site, see the console of your webpage maybe you got some error.

You can debug also by putting that iframe into any page Textarea field where you already use the HTML content of your website.


Drupal 7 pass a custom form fileds input as arguments to the url on submit How can I pass fields input as arguments to the url on custom form submit? I tried the following:

function custom_form_form($form, &$form_state) {

  $form['location'] = array(
    '#type' => 'radios',
    '#title' => t('Location'),
    '#options' => location_options(),
    '#default_value' => '',
    '#required' => TRUE,
  );

  $form['#submit'][] = 'custom_form_submit';
  return $form;
}

function location_options() {
  return array(
    'to' => 'To USA',
    'within' => 'Within USA',
  );
}

function custom_form_submit($form, &$form_state) {
  // I need a function here to redirect to a url with something like
  // move-quote?location=to
  // I tried $form_state['redirect'] but didn't work
}

$form_state['redirect'] = array(
  'move-quote',
    array(
     'query' => array(
       'move-quote' => $form_state['values']['location'],
     ),
    'fragment' => 'optional',
  ),
);

should work in your submit function. Try also

$form['#submit'][0] = 'custom_form_submit';

and clear your caches.
Also http://drupal.org/node/291680 was helpful


How to resolve error "Failed to load MailChimp PHP library. Please refer to the installation requirements."? I'm try to set up Mailchimp module but i keep geeting
Failed to load MailChimp PHP library. Please refer to the installation requirements.

My steps:

disable mailchimp module
install composer_manager package locally
run: curl -sS https://getcomposer.org/installer | php on my root
change composer.json(which lay on my root) - see it below
run: php composer.phar install --no-dev
mailchimp/mailchimp directory is installed in my /vendor folder
clear cache, re=enable module but still getting the error. In my report i see that the module cannot be found.

What i'm doing wrong??

{
    "name": "drupal/composer_manager",
    "type": "drupal-module",
    "description": "Composer Manager is a bridge to best-in-breed, standards compliant PHP libraries that are managed by Composer and Packagist.",
    "homepage": "http://drupal.org/project/composer_manager",
    "license": "GPL-2.0",
    "authors": [
        {
            "name": "Chris Pliakas",
            "email": "opensource@chrispliakas.com",
            "role": "Project Lead"
        },
        {
            "name": "See contributors",
            "homepage": "http://drupal.org/node/1929436/committers",
            "role": "Developer"
        }
    ],
    "support": {
        "issues": "http://drupal.org/project/issues/composer_manager"
    },
    "require": {
        "php": ">=5.3.0",
        "mailchimp/mailchimp": ">=2.0.4"
    }
}

MailChimp module => 7x.3-3

mailchimp library => 2.04

Here are some steps to troubleshoot this error according to this thread: Issue #2054037 Failed to load MailChimp PHP library. Please refer to the installation requirements. (provided by @rtome, above)

Re-read the instructions in MailChimp module's README.txt
Clear the cache
Ensure Libraries module is installed and is working properly
Ensure Mailchimp library is located at sites/all/libraries/mailchimp
Check your versions:

  MailChimp module 7.x-2.x requires MailChimp library 1.3
  MailChimp module > 7.x-3.x requires MailChimp library 2.04

If MailChimp library updated, reinstall MailChimp module


How to hide a sub level menu from being expanded? When a menu is active, drupal displays the sub-menus of the active menu, but because I use the sub-menus in a separate block via the "menu block" module, I don't want the sub-menu to be shown. How can I do it on server side?

Is there an easy drupal way to do it without touching the theme_menu_link? If not, Is there a way to do it in a module rather in template.php? beside, can some one show me how to write the code?

In the Add/Edit menu_block options, you can specify the Maximum depth of the menu tree to 1.


Is it possible to make a second "edit account" page that only allows users to edit some profile fields? So here is my situation: users on my site have to fill out  a rather large number of fields upon registration.  However, after they register, only four (out of about twenty) of these fields need to be changed regularly.  I would like to create a separate "edit" page to allow users to modify just these four fields to keep things simple.

field_checkbox_a
field_checkbox_b
field_checkbox_c
field_checkbox_d

These fields are all contained in a field group, so ideally the page would show this field group, the four checkboxes inside it, and then have a submit and cancel button, that's it.

I want to do this as a separate page, not in-place editing like the Quick Edit module.

Users still need to be able to access the original edit account page to change their timezone, e-mail address, etc. but I could really use a separate screen to allow them to edit the most common account options.

I had the same situation before and handle it with power full druapl feature hook_form_alter, we have 2 forms for user, registration and user edit

user_profile_form ( in editing)
user_register_form (in registration)

We just need hide your specified fields in edit manner So in your custom module

function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    global $user;

    if ($form_id == "user_profile_form") {
       // ym($form);
       // you also can perform this action for specified roles
        //if (!(in_array('blogger', $user->roles) || in_array('administrator', $user->roles))) {
            hide($form['field_mytest']);
            // hide other field with this method
        //}
    }

}

After that  field exists in registration as you can see below

and not exist (hide) in edit  manner

Also you can set them read only instead hiding them with $form['field']['#access'] = FALSE;

And another solution is using field permission module

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.
  Features:

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.

As features that this module provides for us anonymous user( un-register user can edit those field and register user only see(readonly manner).


How to Override OG Group Owner Permissions for view/edit group content? So I have a group content type called student portfolio, which is managed by the student. Then I have a group content node type called endorsement that can be written by professors that are group members.

Question 1: How do I prevent students from editing endorsements? There is no checkbox anywhere in my configuration that says the student role can edit endorsement. Also, on my group permissions, for Members, only "Edit own Endorsement content" is checked, but the student can still edit, which seems like a bug if you ask me.

I'm thinking I'll need some sort of hook_menu_local_tasks_alter() code, but just wanted to verify.

Question 2: How do I prevent the student from even viewing a group content page type? (This is a different project.) On the group page, I think this is just a simple matter of setting the permission on the pane, but I also don't want students to be able to view the stand-alone page.

Because group owners are considered the equivalent of "Super administrator" (user 1) of their group AND group content, which I happen to totally disagree with, this wound up being solved using hook_node_access() as follows for Question 1:

/**
 * Implements hook_node_access().
 *
 * Runs every time a user tries to edit an endorsement
 */
function icme_admin_node_access($node, $op, $account) {
  if ($node->type == 'endoresment' && $op == 'update') {

    // Does the user explicitly have create/edit endorsement content access?
    // By default, the OG module provides group owners add/edit/delete access
    // to all group content
    $ua_create = user_access('create endoresment content');
    $ua_edit = user_access('edit own endoresment content');
    if (!$ua_create && !$ua_edit) {
      // Show access denied message, and, interestingly enough,
      // also sets the permission for the edit link.
      return NODE_ACCESS_DENY;
    }
  }
}

Question 2 is similar, but just need to change $op == 'update' to $op == 'view'.

I'm curious to see if anyone posts a better solution (other than fixing the OG module).


Drupal 7, hook permission for view published content only for certain content type/blog I disabled the view published permission for anonymous user. but I wanted to allow anonymous user to view the blog section with views on it, and I cant seem to hook permission on that particular blog.

is there any clue for this?

thank you

You can use content_access module, you can control any content type permissions individually. here is a nice video tutorial


how to map comments in drupal migrate module So im migrating comments from a different database to Drupal 7 but i cant understand why this wont work. Im successful with migrating nodes, i only mapped the node fields and somehow its node_revision seemed to have automatically updated too.

But in comments it doesnt work, i know to add a comment these tables are affected in drupal:

comment
field_data_comment_body
field_revision_comment_body

am i missing some mapping here in my code?

$this->addFieldMapping('cid', 'id');
    $this->addFieldMapping('is_new')->defaultValue(TRUE); // i dont know what this thing does

    $this->addFieldMapping('nid', 'mainthread');
    $this->addFieldMapping('pid', 'parent')
         ->sourceMigration('ForumComment')
         ->description('Parent comment.');
    $this->addFieldMapping('comment_body', 'body');
    $this->addFieldMapping('subject', 'subject');
    $this->addFieldMapping('hostname', 'host');
    $this->addFieldMapping('created', 'date');
    $this->addFieldMapping('changed', 'last');
    $this->addFieldMapping('name', 'author');
    $this->addFieldMapping('status')
         ->defaultValue(COMMENT_PUBLISHED);
    $this->addFieldMapping('comment_body:format')
        ->defaultValue('full_html');

    /*$this->addFieldMapping('uid', 'accountid')
         ->sourceMigration('WineUser')
         ->defaultValue(1); */

    //optional
    //$this->addFieldMapping('tid', 'category_id');
    //$this->addFieldMapping('comment_count', 'hits');

    // Unmapped destination fields
    $this->addUnmigratedDestinations(array('uid', 'thread', 'mail', 'homepage', 'language', 'comment_body:language'));

      $this->addUnmigratedSources(array('category_id'));

and is my destination correct? here it is:

$this->destination = new MigrateDestinationComment('comment');

based on my code only the comment table is mapped, i just assumed that the body and its revision will automatically map too like in my migration of nodes.

Help please

I got it, you need to add another class for the mapping of the body of the comment

and the destination should be 'comment_node_forum'


Field language - Multi language I have a node in Dutch and I want to get the field in this language.
When I do:

$node->field_name[$node->language][0]['value'];

I get the error:

Undefined index: nl

So I try:

$node->field_name[$node->language]['nl']['value'];

But that doesn't work. What am I doing wrong?

Edit:

I already figured it out:

  $language = field_language('node', $node, 'field_yourfield');

This gave me the language of the field and it was 'und' and not 'nl' as I thought it would be. The language of the node can be different then of the field. Learnt a lot about i18 & Drupal :)

I use a function from this blog post to retrieve the fields value, it's quite handy as it allows you to parse the different values of the field (also it handles value or nid).
Drupal 7 tip : Get field values from entity objects like nodes, users, taxonomy...

Regarding the und, I'm not very sure why is this happening, I saw this issue: Field display languages are cached before locale has changed field language, but I have to wrap my head against this.


Using image styles and term references I have a taxonomy called sponsors with an image field attached. Then I have a content type with a field-collection and inside of the field collection I have the term reference.  So when the admin creates a content type they can choose a sponsor and I setup a view to show the image.  However, they would like to have 3 different sizes to choose from when creating the content.  Is it possible to provide them with a choice of image styles almost like the Insert module let's you do?

UPDATE:  Looks like it's going to be custom code.  The formatter module is nice, but it does not suite the needs for my particular use case.

The Formatter Field module was made for just that:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

There are some steps on the module page I'd recommend reading before diving right in, it's not immediately obvious how to make this module work.


What is the correct core update workflow? I want to use composer to manage Drupal 8 dependencies, but I'm not sure what is the right core update workflow.
At the moment I'm using drush to update core to latest beta release, but I also have some dependencies in my composer.json file, so after the update I'm using composer install to install all the contrib vendor dependencies.
It appears that running composer install overrides some files in the core directory, although I've just updated core to latest version.

I've also tried to manually edit the composer.json file and replace the "drupal/core" line with the specific beta release, e.g. "drupal/core": "~8.0-beta14",, but it still overrides files in the core directory.

What is the right workflow?

I presume that you are using drupal-composer/drupal-project as the basis for your project.  If not, take a look at that project, and compare it with yours.

Also, you said that you want to use composer to manage Drupal 8 dependencies, so I presume that you have selected your contrib modules via composer require drupal/devel rather than drush dl devel.

If you are doing all of these things, then you should use composer update to update Drupal core and all of your contrib modules.  As long as you retain your composer.lock file, composer install should not change the version of any of your dependencies.  You should not use drush pm-update at all.  It should not matter to you whether or not files in the core directory are updated or not, as this directory is managed by Composer.  You are better off not committing composer-managed directories to your repository, although you can if you wish.

Of course, you should run drush updatedb whenever composer update replaces Drupal core or any module.

To avoid getting development versions, set your minimum stability to 'beta' in your composer.json file using Composer stability flags.

If you are using drupal-composer/drupal-project to manage your site, then all of the root-level files such as README.txt, .htaccess and index.html become owned by your project. That means that you should check them in to your git repository; Composer will not update them, you must update them yourself when they change.  These files should change only rarely, but drupal-composer/drupal-project has a script to update these files.


How to remove content from view once user clicks on it (or reads it) in drupal 7? I have a view "Recent content of your interest" based on taxonomy and flag.

Current scenario:

User clicks on content from view and reads it, he comes back to same view.

What I want:

User clicks on content from view, read it, come back and the content (which he just read) is not listed i.e. removed from same view.

Any module I can use for same or any pointer to implement same functionality highly appreciated.

You can use rules and flag module.

Create a view that list related content that the user hasn't flagged.

Create a rule that flags the content when is viewed by the user.

Setup the flag so the it doesn't show up on the node view.


After any AJAX form event, all Entity Reference Fields are blank After any AJAX event in the form (Upload image, add a new field collection row etc.) All Entity Reference fields go blank.

I have multiple entity reference fields, all using a view to get list options.

The issue is occurring on the node edit form.

On first page load, all entity form values are there, and you can edit and save them with no problems. However, If you edit any field that uses AJAX to update, then after ajax has run, all of the entity reference fields lose their options and only show "None" as the single option.

Can anyone think why this would be happening, and what steps I can take to either provide more info, or find a fix?

After using an AJAX field, and then trying to save the form, I get this error in watchdog,

TYPE    form
DATE    Tuesday, 21 June, 2016 - 08:47
USER    collins
LOCATION    http://couplespage.com/node/23/edit
REFERRER    http://couplespage.com/node/23/edit
MESSAGE Illegal choice 7 in Venue element.
SEVERITY    error

This obviously happens because the select lists are all empty, and illegal choices are detected.

http://tinypic.com/r/2pod2dy/9

Update:
On further inspection, using dsm($form) to print krumo and check the results, after ajax, it takes over a minute to complete the page, but all of the values are still there in the array, just not in the actual select list. They are also still there in the page source. Something is making them not show. I will look into someway to rebuild the form after ajax, but Im grabbing at straws here.
Any help really appreciated.

Update 2:
On even further inspection. Values are only lost when it is a view Entity Reference display that is being used to populate the values. When reverting to a simple filter by bundle list, they show after ajax. Something is causing the view to lose its results after ajax.

I finally solved this.

There is a patch here... https://www.drupal.org/files/issues/entityreference-use-tokens-2010898-126.patch That allows you to use tokens in the Entity Reference Fields "Pass argument to view" field.

The problem was that after AJAX, the view I was using for the Entity Reference was losing its contextual filter argument. This patch, and the use of the token fixes the problem nicely.


How to correctly modify Taxonomy Term selection Plugin I want some slight modifications of Drupal\taxonomy\Plugin\EntityReferenceSelection\TermSelection::getReferenceableEntities(), for example to not use - to indicate term hierarchy. How can that be achieved?

I tried to extend that class in a custom module like that:

/**
 * Provides specific access control for the taxonomy_term entity type.
 *
 * @EntityReferenceSelection(
 *   id = "default:custom_taxonomy_term",
 *   label = @Translation("Custom Taxonomy Term selection"),
 *   entity_types = {"taxonomy_term"},
 *   group = "custom",
 *   weight = 2
 * )
 */
class CustomTermSelection extends TermSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    // Customization will be here...
  }
}

The plugin seems to be detected, it appears while debugging $selection_plugins in Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::fieldSettingsForm(), but it won't appear as reference method on editing the term reference field.

What else do I need to modify to get it work?

The annotation in the sample code of my question was wrong. With the help of the first comment to this issue I was able to solve the problem (see accepted answer there). Although this question is a bit different it might be marked as duplicate to How to display more than 10 items in link widget autocomplete?.

Anyway I want to leave the custom plugin including the annotation:

<?php

namespace Drupal\custom\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\taxonomy\Plugin\EntityReferenceSelection\TermSelection;

/**
 * Provides specific access control for the taxonomy_term entity type.
 *
 * @EntityReferenceSelection(
 *   id = "custom:taxonomy_term",
 *   label = @Translation("Custom Taxonomy Term selection"),
 *   base_plugin_label = @Translation("Custom Taxonomy Term selection"),
 *   entity_types = {"taxonomy_term"},
 *   group = "custom",
 *   weight = 2
 * )
 */
class CustomTermSelection extends TermSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    if ($match || $limit) {
      return parent::getReferenceableEntities($match, $match_operator, $limit);
    }

    $options = [];

    $bundles = $this->entityManager->getBundleInfo('taxonomy_term');
    $bundle_names = $this->getConfiguration()['target_bundles'] ?: array_keys($bundles);

    foreach ($bundle_names as $bundle) {
      if ($vocabulary = Vocabulary::load($bundle)) {
        if ($terms = $this->entityManager->getStorage('taxonomy_term')->loadTree($vocabulary->id(), 0, NULL, TRUE)) {
          foreach ($terms as $term) {
            $options[$vocabulary->id()][$term->id()] = Html::escape($this->entityManager->getTranslationFromContext($term)->label());
          }
        }
      }
    }

    return $options;
  }

}

One thing I want to point out, which was not part of the above linked answer is the base_plugin_label = @Translation("Custom Taxonomy Term selection") (solution found on d.o. issue). Without that I got the following notice:

  Notice: Undefined index: base_plugin_label in Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem->fieldSettingsForm() (line 336 of core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php).


Anchor links to paragraph content I have some drupal 8 sites that make heavy use of the Paragraphs and Bootstrap Paragraphs modules.

Some of my users want to be able to create anchor style links to specific paragraph items on pages. For example; a user may wish to link directly to a specific accordion that is halfway down the page. They may wish to do this either from the body of the same page or with an anchor style hyperlink from elsewhere on the site. eg: mysite.com/mypage#myanchor

Other than adding a "name" field and creating a specific "anchor link" twig override for every paragraph type and field is there a more straightforward way of doing this?

In messing around with the anchor_link module It seems it can only find anchors in the body of a node. If you add an anchor to say, the body of an accordion the link function cannot see it.

First you need to set up an ID for the paragraphs. You can do this in oko_preprocess_paragraph():

/**
 * Implements template_preprocess_paragraph().
 */
function THEME_preprocess_paragraph(&$variables) {
  $variables['paragraph_id'] = $variables['paragraph']->id();
}

Now, you can output the ID of the paragraph using {{ paragraph_id }} in any paragraph templates you have. So you can copy paragraph.html.twig to your theme, and change this:

<div{{ attributes.addClass(classes) }}>

To this:

<div{{ attributes.addClass(classes) }} id="paragraph-{{ paragraph_id }}">


delete profile2 profile from a user I am using Profile2 on my site, with 3 different Profile2 Profiles set up: A, B & C. These are matched to roles A, B and C.

Users can only create and edit a profile that matches their role, though C users may also have A or B profiles.

While logged in as an administrator, I accidentally added a Profile2 Profile  of type C to a users account who only has role A. (Admins can add profiles of any type to existing users.)

I cannot for the life of me find a way to delete the C Profile for this A user. What am I missing? Isn't there any admin tool to remove Profile2 data from a user? The Profile2 page to edit the C Profile only has a "Save" button at the bottom, not a "Remove" or "Delete" button.

You need to have the "Administer profiles" permission.

Then you will have a "Delete profile" button at the bottom of the profile page when editing.

You can also access the profile at: /profile-<profile_type>/<uid>/delete and go right to the deletion confirmation box. Note that the path is compose of the word 'profile' then a hypen then the name of the profile type you created, so in your example it would be: /profile-C/<uid>

HTH.


How can create a download counter? How can tracks downloads of private files attached to nodes via the core upload or contributed filefield modules for custom content type, I created a file field and I simply want to count the number of times have been downloaded this file and display this count number in node template?

My Project purpose:

Upload a file as Admin, or any authenticated user
Store the file in a private directory (But accessible by public
users)
Allow the all people or anonymous users to download the files.

These are some details about my content type module.

Module name: My Module
Content type name: My Content
Field Type: File
Display Format: URL to file (or Generic)
Field name: field_file

I know that there are some module like:

File download count
Download Count
AJAX Download Counter

For drupal 7, but seem  none of them work in drupal 8.

Thanks for any help.

The only Drupal-centric of doing this is by making sure your content type is utilizing the Private files directory for your file field. Otherwise, downloads are served by the web server.

When private file storage is utilized, this enables Drupal as the file download gatekeeper through its /system/files/{filepath} route. When the controller for the download route is called, it evokes hook_file_download() which can be used to store your ongoing file download count.

For example a custom module could implement:

/**
 * Implements hook_file_download().
 */
function MYMDOULE_file_download($uri) {
  // @TODO: Store/Increment count for unique $uri.
}

Then reference the count when building variables for your node template:

/**
 * Implements hook_preprocess_node().
 */
function MYTHEME_preprocess_node(array &$variables) {
  if (isset($variables['node']->field_MYFILE_FIELD)) {
    $uri =  $variables['node']->field_MYFILE_FIELD->entity->getFileUri();
  } else {
    $uri = '';
  }
  // @TOOD: lookup count for $uri and inject it into
  // $variables['field_MYFILE_FIELD_count'] for display
}


How to create a views that display all the publish content type as one output per user Intro : I have created a two different content types because I needed two different moderation process for those two content type, each of those content type are limited to 1 per user. Those content are "Projet Description" and "Projet Images".

Now I need to combine those two content types into one with views so I can show the user projet and is related images. The problem I have for the moment when I group result together by UID is that the two node hare display separately and I see a Title for the Projet but I also see a Title for the Images.

What I need is :

USER 1
Title : My Projet Titre
first image for this project: (image1)

USER 2
Title : My Super Projet
first image for this project: (image1)

What I have for the moment is :

USER 1
Title : My Projet Title

Title : Images for the Projet
(image 1)(image 2)(image 3)

USER 2
Title : My Super Projet

Title : Images for the Projet
(image 1)(image 2)(image 3)

PS: I try to keep that as one question but I also need to have a exposed taxonomy filter for Projet

I finally did that with Relation module. I was assuming I don't need that because there is a relation between the two content type, the author is the same for the two node, but I was not able to combine the two node in one.

My solution Relation Module to combine the two node. I created a relation between the project and the project images node. In views I created a content type view with the field I need from the project type than I add the relation : Relation(node <-> node) add I add the field "Image(from Projet Image)" to display the image and Bingo I have one view output for two different node.

To make the relation automatic I created a Rules with Rules module. I fire the rule when a Projet is added or a Projet Image is added than I create the relation.

A quick help for rules 5 actions step
1st action : create a variable / create a list
2st action : fetch entity by property / node / Author
3rd action : place the fetch result in the list created at step 1 (you may have to create a lot) personally because the node hare limit to 1 per content type per user I just repeats the step 3 two time
4ft action : create a entity / relation / with the list created at step 1.

Those step have to be improve because those are my first step with Rules and I rules are not strong at all.

Hope it help someone.


Create basic field data in template like node for custom entities {{ custom_entity.id }} I see node preprocess does this
$variables['node'] = $variables['elements']['#node'];
and then in the template one can do this
{{ node.id }}
but when I create a custom entity and do the same,  I never get past all the the errors like
Exception: Object of type Drupal\Core\Field\FieldItemList cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 476 of core/lib/Drupal/Core/Template/TwigExtension.php).

What are they doing special for node?

Why does {{ custom_entity.id }} produce this error message?

Exception: Object of type Drupal\Core\Field\FieldItemList cannot be
printed.

If your entity defines id for the entity ID then {{ custom_entity.id }} is ambiguous. It can mean the object property (the ID field) or the method EntityInterface::id().
So use parentheses to make it clear it is a method:
{{ custom_entity.id() }}

Or retrieve the field value when you have already a field as the error message shows:
{{ custom_entity.id.value }}

What are they doing special for node?
The node entity is using nid as ID field, so id and nid are unambigious.
Method id():
{{ node.id }}

Field nid:
{{ node.nid.value }}


Is it possible for a site owner's user account to **ever** have a permissions issue? I continually read posts like this:

  This may sound dumb, but have you set the proper permissions to use it? I spent a good two hours trying to figure out what I was doing wrong before realizing I hadn't checked the '[whatever]' box.

As a Han-Solo of D-developers, I never think of permissions, but at desperate moments when Views repeats the same imperious error, doubt creeps in. Could it be permissions?

User #1 only bypasses user_access(); if something runs its own access calls, and doesn't call user_accces(), that user won't get any special handling.


where to put addCommand when implement ajax callback commands i' m trying to load a dynamic value on every node of my site and i want to achieve this via ajax callback commands and writing custom module
so i have a class  in src/ajax folder of module like:

class TestCommand implements CommandInterface
{
..
  public function render() {
    return array(
      'command' => 'test',
      'text' => $this->message,
    );
  }
}

also a js file:

(function($, Drupal) {
  alert('loaded');
  /**
   * Add new command for reading a message.
   */
  Drupal.AjaxCommands.prototype.test = function(ajax, response, status){
    alert('called');
    console.log(response);
  }
})(jQuery, Drupal);

but i don't know where i am supposed to put this below lines to call command on every node/view.
if i put this in mytheme_preprocess_node -checking with var_dump()- i can see
correct response but it doesn't call Drupal.AjaxCommands.prototype.test

  //where to put this lines to call test command on every node view.
  $response = new AjaxResponse();
  $response->addCommand( new TestCommand('someparam'));
  return $response;

js file is loaded because i get 'loaded alert'.

lots of examples on sites, call this via ajax callback in form.
one have different approach but i don't know how to apply these solutions in my situation.

You put it in a controller like shown in the linked question, not the answers. Then this topic might be helpful how to trigger the ajax controller: How to Trigger Existing, Non-Form Ajax from JavaScript Event

For passing the node ID to the controller use a route parameter:

myModule.myRoute:
  path: '/myajax/node/{node_id}'
  defaults:
    _controller: '\Drupal\myModule\MyController::getNode'
    _title: 'Node'
  requirements:
    _permission: 'access content'

Now you can add the node ID to the endpoint url

var url = '/myajax/node/' + node_id;
Drupal.ajax({url: url}).execute();

and received it by the controller:

public function getNode($node_id) {


What is FID and how does it works? I could not find a clear explanation about what is a 'fid'. I got is an identifier for file in drupal, but no more than that. How it is generated? Is unique for any file? When it is used and why? Could someone give a clear explanation of this entity?

You can find fid under the table name file_managed.
It is unique id for files. In files you can include images, .txt, .pdf etc extension files.
This fid is unique for the site and auto incremented
By using file_load($fid) function. Where $fid is file id.

Fid is only valid for managed files. Files uploaded as unmanaged does not have records in database, so no fid.


use custom tokens on a webform email confirmation I have written a custom module which defines some tokens. These tokens are used e.g. in Wysiwyg editor this way: [mytype:closing_date] (I have token_filter module)

Is it posible to make these tokens available also in the Webform module, and specifically in the confirmation e-mail that is sent after filling the form?

I tried %mytype[closing_date] but didn't work.

use also the token module, you'll find instructions in its documentation.

basically, you'll need to implement these two hooks:

function my_user_token_values($type, $object = NULL, $options = array()) {
  if ($type == 'user') {
    $user = $object;
    $tokens['name']      = $user->name;
    $tokens['mail']      = $user->mail;
    return $tokens;
  }
}

and

function my_user_token_list($type = 'all') {
  if ($type == 'user' || $type == 'all') {
    $tokens['user']['name']      = t("The user's name");
    $tokens['user']['mail']      = t("The user's email address");
    return $tokens;
  }
}


form does not validate function formexample_nameform(){

$form['user_name'] = array(
'#title' => t('your name'),
'#type' => 'textfield',
'#description' => t('Please enter your name.'),
);

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

return $form;
}

if i add this:

'#name' => 'new name attribute',

it looks like this:

function formexample_nameform(){

$form['user_name'] = array(
'#title' => t('your name'),
'#name' => 'new name attribute',
'#type' => 'textfield',
'#description' => t('Please enter your name.'),
);

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

return $form;
}

and it does not validate any more, it always let the inputs pass through.

my validate function:

function formexample_nameform_validate($form, &$form_state){
if ($form_state['values']['user_name'] == 'King Kong') {
    form_set_error('user_name',
    t('King Kong is not allowed')
    );
}
}

question: what has the name attribute with validation to do?!

As per the FAPI the element textfield has no name attribute

Available Properties are

#access, #after_build, #ajax, #attributes, #autocomplete_path (default: FALSE),
#default_value, #description, #disabled, #element_validate, #field_prefix, #field_suffix,
 #maxlength (default: 128), #parents, #post_render, #prefix, #pre_render, #process, #required,
 #size (default: 60), #states, #suffix, #text_format, #theme, #theme_wrappers, #title,
#title_display, #tree, #type, #weight

I am not sure about the reason that the form is not validating, Excited to know the reason.


how do I use overlays in d7? Does Drupal 7 have built-in functionality for using jquery overlays? I would like to do some confirmation screens and form-wizard type stuff with them.

Have you checked: How to Add a jQuery UI Dialog to Drupal 7?

There is also Drupal 7 jQuery (Popup e ui.dialog), in Italian.


Specify what the Facebook "Like it" button shows on Facebook On our website we have a Facebook "Like it" button, which works fine, but if someone "likes" us, Facebook shows an ugly picture.

As we want Facebook to link to the same content on every page, also on pages which are not driven by a node but by a view, this makes Drupal node based meta tags and open graph useless, is it?

How can we tell Facebook what to show about our website?

You can also look into the Open Graph meta tags module which allows you to specify which fields Facebook looks at when constructing its likes.


Two Views with autocomplete filters display no result I have 2 views-blocks with autocomplete filters, both filters are for the title field. And autocomplete filters display no result when the views are placed on the same page.
How to make them to not conflict with each other?

I use this module Views Autocomplete Filters

The link provided by  WaQaR Ali solved the problem.

  The problem lies in the fact that two form-fields get the same ID.
  Placing this code in a hook_form_FORM_ID_alter():

<?php
 $form['title']['#id'] = 'form-text-' . rand(0,100);
?>

Thank you Ali!


Node urls indexed by Google I am pretty new to Drupal, can someone tell me why ive got lots of node urls in my index on Google, is this because i havent given the post on my site a friendly url ?

Is there a way to fix this or do i have to edit every post with a node url ?

Is there a way to stop this happening in future

JC

If you want to reduce the content indexed by search engines use your robots.txt file to instruct them to ignore certain paths or sets of paths.

Many Drupal projects use Path, Pathauto and one of redirect modules to automatically assign aliases to links. Usually, the path pattern is set to automatically replace node/[nid] with something like content/[title]. Globalredirect or Redirect modules permanently automatically redirect from the default Drupal query to the alias, so there is nothing else you have to do (no need to edit Robots.txt unless you want to exclude some of them).

Path aliases can be generated automatically for existing content so it will work for your case and also in the future.


display a complete node i want to display a node (from a menu callback), but when i do this:

echo node_view(node_load($_POST['classid']));

it displays the node without the page template. How do show the entire node, just like someone navigated to '/node/xxx'.

by the way, i can't just redirect to 'node/xxxx' because i need to leave the url without any parameter (stupid requirement by employers)

It's a bit strange that node_view is not returning a fully formatted node. The node module calls node_view inside it's own hook_menu to handle node/%nid requests.

Is there any chance that your CSS is selecting on something specific to node/%nid pages or your templates are setup in a non-standard way.

Can you show us the exact HTML string that is being returned by that function and the HTML string you are expecting?


htaccess for Angular app in a subfolder I have an Angular 6 app living in a subfolder on a D8 installation. I have no issues navigating to the app and the angular routing doing it's thing as I navigate the app. My issues is I get a Drupal 404 if I try to hit the sub routes directly in the address bar.

What do I need to add to my htaccess that will let Drupal ignore the folder and the angular routing still work?

Drupal: localhost:8888

Angular: localhost:8888/my-app

Things I've tried:

Adding: RewriteCond %{REQUEST_URI} !^/my-app/.*$ <- I get Not Found

Changed DirectoryIndex index.php index.html index.htm to DirectoryIndex index.php

Adding the following to httpd.conf:

<Location "/my-app">
 FallbackResource /my-app/index.html
</Location>
<Directory /my-app>
 FallbackResource disabled
</Directory>

You need to add the following rewrite in your Drupal .htaccess

RewriteCond %{REQUEST_URI} !/APP-FOLDER-NAME/.*

Then in the root of the angular application folder you need the following in your .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) /APP-FOLDER-NAME/index.html [NC,L]


How to manipulate different regions from a module My module has a menu callback which outputs data to a custom template using hook_theme().

Normally, Drupal includes this output into the content region that is rendered at the page.tpl.php level using render($page['content']).

How can I simultaneously output stuff from my module but into other regions of page.tpl.php? For example $page['sidebar_first'] or $page['footer'].

Is this possible?
Alternatively, how can I tell Drupal to use a custom page.tpl.php when the menu callback is called?

If you want to exactly put content in $page['sidebar_first'], then you can implement hook_page_build() or hook_page_alter(). The difference between the hooks is that the latter is used when the module needs to alter some elements added by another module with hook_page_build() as the first hook is executed first.

Examples of hook_page_build() are the following functions.

function toolbar_page_build(&$page) {
  $page['page_top']['toolbar'] = array(
    '#pre_render' => array('toolbar_pre_render'),
    '#access' => user_access('access toolbar'),
    'toolbar_drawer' => array(),
  );
}

function dashboard_page_build(&$page) {
  global $theme_key;

  if (dashboard_is_visible()) {
    $block_info = array();

    // Create a wrapper for the dashboard itself, then insert each dashboard
    // region into it.
    $page['content']['dashboard'] = array('#theme_wrappers' => array('dashboard'));
    foreach (dashboard_regions() as $region) {
      // Do not show dashboard blocks that are disabled.
      if ($region == 'dashboard_inactive') {
        continue;
      }
      // …
    }
    // …
  }
}

As alternative, your module could define a block, but in that case, the block will be placed in the region set by the administrator users (or any user with the right permission), which could be place the block in a different region. If there isn't a reason to place the content your module is adding in a specific region, then I would rather opt for implementing blocks.


How to show/hide fields with the Rules module based on the user's language? I have a multi-language support website.

My question: can I show/hide some fields based on the user's language choice with Rules module?

The Conditional Fields module might be of help to you.


How to override node content in Drupal 7 So I see in the archives how to override a node's $title (How do I overwrite node title for specific content type?), but how would I override the node's content in Drupal 7? I see that Drupal 7 no longer uses $vars['content'], which was really handy in Drupal 6

In Drupal 7 the content is in $content.

See node.tpl.php

<?php print render($content); ?>

The $content definition:

  An array of node items. Use render($content) to print them all, or
  print a subset such as render($content['field_example']). Use
  hide($content['field_example']) to temporarily suppress the printing
  of a given element.


Change Exposed Filter from Dropdown to List How can one change an exposed filter format so it is displayed as a list rather than a dropdown list? If it is relevant, I am using the Better Exposed Filters module.

Go to BEF settings in the view....

Find your exposed filter, and choose the display type. (list)


How do I create a template for custom display mode of user registration form? I have multiple registration pages, each with corresponding to a form display under
admin/config/people/accounts/form-display.
I added this to Mytheme.theme

function Mytheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#id'])) {
    $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']['#id']);
  }
}

Then I can create a template form--user-register-form.html.twig but that will affect all the form display modes. Is it a way to create a template for each display mode? For instance for a form display "Allied" something like form--user-registration-form---allied.html.twig ?

If you want to add template by Form mode try the following:

/**
 * Implements theme_theme_suggestions_alter().
 */
function YOURTHEME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if ($hook == 'form' & !empty($variables['element']['#id'])) {
    /** @var \Drupal\Core\Entity\Entity\EntityFormDisplay $form_display */
    $form_display = $variables['element']['#process'][1][0] ?? NULL;
    if ($form_display) {
      $suggestions[] = 'form__' . str_replace('-', '_', $form_display->getMode());
    }
  }
}


Simplenews unsubscribe link shows a 404 Page In my Newsletter the unsubscribe URL which is inserted by a token, returns a 404 page.
The URL of my Link is:

http://www.mysite.info/newsletter/confirm/remove/

What could be the issue?

There are many issue thread on simplenews about this issue.

Simplenews 404 issues

Currently the only supported version of simplenews is version 6.x-1.3 (May 21st 2010).   Most of the issues have patches that are commit to 6.x-2.x-dev and 6.x-2.0-alpha2.  You might want to upgrade.  If you don't, then you will need to apply one or multiple patches to fix your problem.


Form elements validation order I have a custom autocomplete field widget, defined like below:

/**
 * Implements hook_field_widget_form
 */
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#id' => 'mymodule-field',
    '#type' => 'textfield',
    '#default_value' => '',
    '#autocomplete_path' => 'some/path',
    '#element_validate' => array('mymodule_autocomplete_validate'),
  );
  return $element;
}

I have a content type with 2 Term reference autocomplete fields: field foo with standard Autocomplete term widget (tagging) widget, and field bar with my custom autocomplete widget.

Field bar has a higher weight than field foo on a node form.

mymodule has weight 20 in system table. taxonomy module has weight 0.

However, when I submit a node form which includes both fields, mymodule_autocomplete_validate() is invoked earlier than taxonomy_autocomplete_validate(), so $form_state['values']['field-myfield-a'] is not processed yet.

The problem is I need to use the processed value of foo in mymodule_autocomplete_validate().

I have another 2 fields with same widgets but another names, and they are processed in the right order.

So the question is: how the order of execution of these functions is defined? Is there a way to change it?

hook_module_implements_alter() would seem to be the one you are looking for to change execution order.

However, I'm not sure It is exactly what you are looking for because it could have to do with the node edit form. One field could be higher on that form, and that could be causing the validation order issue. The weight of the fields on the form itself could be dictating the validation order. If that is the case, you can hook into the node form and run the validation in the order needed.


access the view but not the node I have a view that displays a list of items. How to make anonymous user see this list of items but when accessing the node, it has to be logged? Any idea?

I use the latest version of drupal

You can disable node_access check for the view (Edit the View → Advanced → Query settings → Disable SQL Rewriting).


Node loses title on submit I am creating a custom module that allows for users to create blog posts that will be private and related to a project. So I created a new content_type called "tasker_blog" that just has a title and body. The user goes to view their projects and clicks a link which takes them to 'tasker_project/%/blog' % being the id of the project. I have the form being displayed correctly but when I submit the form I have two problems,
  1) the title is lost on submit
  2) getting this error: EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids().

Here is the code I have written (some non-relevant parts taken out).

function tasker_project_menu() {
    $items = array();

    $items['tasker_project/%/blog'] = array(
        'title' => 'Private Blog Post',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('tasker_project_blog_form',1),
        'access arguments' => array('view tasker projects'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function tasker_project_blog_form($form, &$form_state) {
    drupal_add_css(drupal_get_path('module', 'tasker_project') . '/tasker_project.css');
    global $user;
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array(
        'uid' => $user->uid,
        'name' => (isset($user->name) ? $user->name : ''),
        'type' => 'tasker_blog',
        'language' => 'und',
    );
    node_object_prepare($node);

    $form = drupal_get_form('tasker_blog_node_form',$node);
    $form['hidden_project_id'] = array(
        '#type' => 'hidden',
        '#value' => arg(1),
    );

    return $form;
}

If I submit with nothing else added I get the error I mentioned above. If I add this (using Kint to display variables):

function tasker_project_node_validate($node, $form, &$form_state) {
    s($_REQUEST);
    s($form_state['values']);
    die();
}

$_REQUEST array output:

array (9) (
    'title' => string (4) "test"
    'body' => array (1) (
        'und' => array (1) (
             array (2) (
                'format' => string (13) "filtered_html"
                'value' => string (13) "
test

"
            )
        )
    )
    'changed' => string (0) ""
    'form_build_id' => string (48) "form-eKWwyFlBOzi4LsajaAiEZBG7J0uOSI1UDVIhiDomeJE"
    'form_token' => string (43) "N421-IiWecixBJGbxTHGcJAIrd6ZutzAW0LAtVSsrJ4"
    'form_id' => string (24) "tasker_project_blog_form"
    'hidden_project_id' => string (2) "10"
    'additional_settings__active_tab' => string (0) ""
    'op' => string (4) "Save"
)

$form_state['values'] array output:

array (27) (
    'nid' => NULL
    'vid' => NULL
    'uid' => string (1) "5"
    'created' => integer 1347038959
    'type' => string (11) "tasker_blog"
    'language' => string (3) "und"
    'changed' => string (0) ""
    'title' => string (0) ""
    'additional_settings__active_tab' => string (0) ""
    'revision' => bool FALSE
    'log' => string (0) ""
    'name' => string (10) "ndenlinger"
    'date' => string (0) ""
    'status' => integer 0
    'promote' => integer 0
    'sticky' => integer 0
    'submit' => string (4) "Save"
    'preview' => string (7) "Preview"
    'body' => array (1) (
        'und' => array (1) (
             array (3) (
                'summary' => string (0) ""
                'format' => string (13) "filtered_html"
                'value' => string (13) "
test

"
            )
        )
    )
    //...MORE HERE REMOVED SINCE NOT RELEVANT
)

So I'm not sure if the two problems are related or not. Once the node is saved I am going to add a row to a custom table that store the nid and the project_id.

Found the solution in case anyone else ever has this issue:

    drupal_add_css(drupal_get_path('module', 'tasker_project') . '/tasker_project.css');
    global $user;
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array(
        'uid' => $user->uid,
        'name' => (isset($user->name) ? $user->name : ''),
        'type' => 'tasker_blog',
        'language' => 'und',
    );
    node_object_prepare($node);
    $form_state['build_info']['args'] = array($node);

    $form = drupal_retrieve_form('tasker_blog_node_form', $form_state);
    drupal_prepare_form('tasker_blog_node_form', $form, $form_state);
    $form['hidden_project_id'] = array(
        '#type' => 'hidden',
        '#value' => arg(1),
    );

I used drupal_retrieve_form and drupal_prepare_form and everything seems to work correctly now. Not sure why drupal_build_form or drupal_get_form don't work correctly.


added in views header section is automatically closed: How do I avoid it? I have added a div in views header (Custom text) section like this

This div's closing tag is added in views footer section. There are some rows  in field section as well. The Display output: template is as below

<?php
  print $header;
  print $rows;
  print $footer;
 ?>

So I am expecting the the result as

  /* header*/

row1
      /* In fields */

row2
      /* In fields */

                  /* In Footer*/

But what I am getting is

row1

row2

The div in header is automatically closed by drupal 7. How can i avoid that

Method 1: Unfiltered text

When setting up the header and footer in your view, select Global: Unfiltered text. For the header enter
 and for the footer type in
.

If you then override the default views-view.tpl.php, stripping out everything except

<?php print $header; ?>
<?php print $rows; ?>
<?php print $footer; ?>

... you should achieve output similar to:

Method 2: Use attachments

This might be ideal if editing the header and footer through the Views UI isn't important, but you want some flexibility in the output that wraps around your rows; for example, if you wanted it to be dynamic.

Override the default views-view.tpl.php so that it looks like this:

<?php print $attachment_before; ?>
<?php print $rows; ?>
<?php print $attachment_after; ?>

In a custom module you would then implement hook_views_pre_render():

function MODULENAME_views_pre_render(&$view) {
  $header_str = '
';
  $footer_str = '
';

  if ($view->name == 'your_view_name' && $view->current_display == 'your_display_name') {
    $view->attachment_before = $header_str;
    $view->attachment_after = $footer_str;
  }
}

(Remember to clear the cache after adding the function.)

Method 3: Simple template override (simplest but least flexible)

Override the default views-view.tpl.php and simply replace all of the mark-up with

<?php print $rows; ?>

Hope that helps!

A couple of links that might be useful:

Views template files
Drupal API hook_views_pre_render()


new comment notification in teaser mode in links Yesterday I saw "2 new comment" in teaser view in one of news in my Drupal-based website. when I click on news and read it and return to news list, the notification was gone. Now I want know where Drupal create this?

There is history db table in Drupal: "A record of which users have read which nodes."
It contains last time when user viewed a node. This data allows to show new content and new comments to user.
Comment module uses it to determine how many new comments appeared while user was not on the node page in comment_num_new() function.
Link “2 new comments” was added by this code in comment.module file through hook_node_view() hook:

  // Show a link to the first new comment.
  if ($new = comment_num_new($node->nid)) {
    $links['comment-new-comments'] = array(
      'title' => format_plural($new, '1 new comment', '@count new comments'),
      'href' => "node/$node->nid",
      'query' => comment_new_page_count($node->comment_count, $new, $node),
      'attributes' => array('title' => t('Jump to the first new comment of this posting.')),
      'fragment' => 'new',
      'html' => TRUE,
    );
  }


Redirect for specific path links I have to make redirect for links:
http://example.com/file/file1.pdf
http://example.com/file/file2.pdf
...
to links:
http://example.com/sites/default/files/file1.pdf
http://example.com/sites/default/files/file2.pdf
...
I've tried .htaccess changing, but fail. (it's too Voodoo for me)
Redirect project has no such function (afaik).
I don't know what hook can I use in my module for such redirect.

How can I make such redirect?

UPDATE:

I've created simple .htaccess file:

  RewriteEngine on
  RewriteRule ^file/(.*)$ sites/default/files/$1 [L]

And it works.

But when I insert in original Drupal .htaccess
line RewriteRule ^file/(.*)$ sites/default/files/$1 [L] after RewriteEngine on
- there is no successful redirect.

Why?

SOLUTION:

  RewriteEngine on
  RewriteRule ^file/(.*)$ sites/default/files/$1 [L, R=301]

As you seem to have learned the Redirect module is really for page-specific redirects (this single URL redirects to that URL), not patterns, as your case seems to require. For this a server-side redirect is really the way to go. Not only is it a standard solution to this kind of problem, but it can happen independent of Drupal, so there is no need to bootstrap Drupal just to process the redirect.

I think the specifics of setting-up a server-side redirect a a bit are a bit beyond the scope of this space (as it's not a Drupal-specific concept), but there are lots of resources out there on the topic, and I think you'll find that it's not too hard. You mentioned that it feels like "Voodo", but I think it will prove far more straightforward than a module-based solution implemented in php. Here's one example stackexchange post that might be relevant to your case.

All that said, because your question does ask for a moudle-specific way to do it, here are some notes on that too. This is much less ideal, as noted above, but it's worth referencing. For this I think you would want to trigger a drupal_goto() inside of hook_init(). A very simple-case example of this pattern can be referenced in this post, and interpolated for your example:

/**
 * Implements hook_init().
 */
function mymodule_init() {
  $path = current_path();
  // preg_match() could also work instead of drupal_match_path()
  if (drupal_match_path($path, 'file/*')) {
    drupal_goto('sites/default/' . $path);
  }
}

I suppose there may be real use cases for this kind of module-based approach, but as I noted above, I really don't think your case is one of them. You would probably be best-served with a service-side redirect (in Apache/.htaccess).


Is the creator of a flag stored in the database? Is the uid of the user who created a specific flag stored in the database? Where is it stored?

Yes, it's stored in the flag_content table, in the uid column which is defined as

  The user ID by whom this content was flagged.


Custom Display Modes on a custom entity type I have created a custom entity type (without bundles) using the Drupal Console command.
Everything works fine with the out the box stuff. I can configure fields, the order of the form and the order of the output display.

However, it seems impossible to add and new View Modes to my new entity type. I have tried adding a new mode to the "Content" view modes section but I don't have the collapsable details section to be able to enable new view modes.

Is there a setting I have missed in the entity code that will display this?

As always, I found the answer just after posting the question.

For others looking for the same thing, you need to create an install .yml file in your custom module.
I found this by looking at the Media module in core.

In your module create config/install/core.entity_view_mode.ENTITY_TYPE_ID.NAME_OF_VIEW_MODE_TO_CREATE.yml that implements the following:

langcode: en # Or your default site language
status: false
dependencies:
  module:
    - my_module
id: entity_type_id.name_of_view_mode_to_create
label: 'My new View Mode'
targetEntityType: entity_type_id
cache: true

I hope this helps someone else too :D


How to add html to the form? I am creating a custom module. I have a form that I would like to add some HTML to, but I don't know what the best way to do this.

In this example, I have a page with a textbox, dropdown list, and text area. I want to add a a div between the dropdown list and text area.  But, I'm not sure how to add raw html to a web form.

Here is what I have:

function myModule_add_form($form_state){
  try{
    $form = array();
    $form['myModule_title'] = array(
      '#title' => 'Title',
      '#type' => 'textfield',
      '#size' => '30',
      '#weight'=>1,
    );

    $form['myModule_type_list']=array(
      '#type'=>'select',
      '#title' => 'Type List',
      '#options' => $someArray,
      '#multiple' => false,
      '#attributes'=>array('size'=>1),
      '#weight'=>2,
    );

    $form['myModule_description'] = array(
      '#title' => 'Description',
      '#type' => 'textarea',
      '#size' => '255',
      '#weight'=>3,
    );

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

    return $form;
  } catch(Exception $e){
      $errrmsg = "Error with creating form: " .$e->getMessage();
      throw New Exception($errrmsg);
  }
}

Thanks
jason

No need to declare a form element as #type = 'markup', as this is the default type.

$html = 'My HTML';

$form['mymarkup'] = array(
  '#markup' => $html,
);

Refer to: https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x


I've got `PDOException: SQLSTATE[HY000] [2002] No such file or directory` when using drush I installed Drush for the first time (so it may be a configuration error) and I'm trying to update to the latest core version of Drupal.

Drush is giving me this error - I'm on an OSX box.

dev5:clientnamedirectory my.name$ drush pm-update projects drupal-7.25

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[HY000] [2002] No such file or directory in drupal_get_installed_schema_version() (line 155 of /Users/my.name/Sites/proface/includes/install.inc).

Additional

PDOException: SQLSTATE[HY000] [2002] No such file or directory in system_list() (line 165 of /Users/my.name/Sites/clientnamedirectory/includes/module.inc).

Drush command terminated abnormally due to an unrecoverable error.

This was how I solved it on macOS:

sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

Source: Working with Drush on Mamp.


Drush error — missing module Console_Table I want to know how may I resolve this issue !!! I'm using Centos Machine and drush

  $ drush status
    Drush needs to download a library from                               [error]
    http://download.pear.php.net/package/Console_Table-1.1.3.tgz in order
    to function, and the attempt to download this file automatically
    failed because you do not have permission to write to the library
    directory /usr/local/share/drush/lib. To continue you will need to
    manually download the package from
    http://download.pear.php.net/package/Console_Table-1.1.3.tgz, extract
    it, and copy the directory into your /usr/local/share/drush/lib
    directory.

I've done what it is said in the request but it still give me the same error :

$ sudo wget http://download.pear.php.net/package/Console_Table-1.1.3.tgz
$ sudo tar -xzf Console_Table-1.1.3.tgz
$ sudo mv Console_Table-1.1.3/Table.php usr/local/share/drush/lib/table.inc

Drush 5 is no longer supported.  Install Drush 8 using the standard installation instructions.


How to programmatically create an image style? I need to create image style programmatically in Drupal 7. I found this issue: https://www.drupal.org/project/drupal/issues/2735969 and much more other issues, but all are for Drupal 8. I can't find anything to Drupal 7. Is that impossible in Drupal 7?

You're looking for the image_style_save and image_effect_save functions.
An example from the comments on the image_style_save docs page:
$style = image_style_save(array('name' => 'avatar'));
$effect = array(
  'name' => 'image_scale',
  'data' => array(
    'width' => 64,
    'height' => 64,
    'upscale' => TRUE,
  ),
  'isid' => $style['isid'],
);
image_effect_save($effect);


Is there a way to integrate revisioning with Panels + CTools content types? I'm using CTools content types to make highly customized Panels panes. The panes together form a Panels Node (I'm using the Panels default module for this).

The Panels node itself can be revisioned, but these revisions do not include changes to the content that lives in the panes. It seems that the content of the panes themselves cannot be revisioned.

Is there a way to use revisions/workflow/workbench/anything to control the publishing flow of the panes?

Unfortunately, I can't think of any simple way to do what you want.

I would probably have solved it by having the content type pull it's content from the entity they are displayed on instead.

It's possible that fieldable panel panes could be useful to you.

In the end, if you really need revisioning on the the content type settings form, you're gonna have to implement it yourself. Since the form is a standard Drupal form, I would try doing it with a node type as backend, instead of doing the whole thing from scratch. You should be able to just load up the edit form for a node, and re-use most of the functionality.


Ajax div update to insert JS for subsequent asynchronous request to external site I wanted to use the postscribe library (https://github.com/krux/postscribe) to make an asynchronous request to google trends, which would update a div with a graph without requiring a page reload.

Using the library on its own through a few methods (drupal_add_js or a custom block) works just fine, but I wish for the js code to be reloaded everytime the appropriate ajax callback is initiated.

$form['trends-visual'] = array(
  '#prefix' => '
',
  '#suffix' => '

',
  '#ajax' => array(
    'effect' => 'fade',
  ),
);

$form['trends-graph'] = array(
  '#prefix' => '
 '
',
);

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

The callback

function trends_ajax_submit_callback($ajax, &$form, &$form_state)  {

 $form_state['rebuild'] = TRUE;
 $commands = array();
 $commands[] = ajax_command_html('#trends-visualization-container',
   '\');
         }
       }
      })(jQuery);</script>');

return array('#type' => 'ajax', '#commands' => $commands);

Triggering the Ajax with $form['submit'] results in the following JS error:

Uncaught SyntaxError: Unexpected token ILLEGAL

This is referencing my JS code, specifically this line:

postscribe('#trends-graph', '

I managed to solve this by escaping one more character and removing one semicolon.

In the 2nd argument of ajax_command_html I was attaching a string which had two script tags, one inner and one outter. The inner closing script tag wasn't being passed unless I escaped its forward slash, like this:

<\/script>

Lastly, I had to remove the semicolon that was following "(jQuery)", just prior to closing the outter script tag, like this:

})(jQuery)</script>');

Hopefully this can be of use to someone!


views exposed form alter hook works with login but not work with out login? I have created views exposed form for searching title based content and i want to display search results into another page for this i have wrote below code in my custom module,it's working fine with login but can't work with out login please advice.

<?php
function module_name_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
 drupal_set_message('Form Hook Called');//just to check that hook is called by drupal
  if($form['#id'] == 'form id here')
  {

    $form['#action'] = base_path().'path';
  }
}

Thanks,

Please check your code on search_redirect_permission.You have to use

access search_redirect module content in user_access function to display result.You have to use search api under anonymus login codition.

Something like:

if (user_access('access search_redirect module content')) {
  // search results!
 } else {
  // no search results!
 }

But I don't understand why you are using hook_permission(),if it should be viewed by anonymous users.

EDIT: For form redirect you should do something like:

function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{

    if($form_id == 'your_form_id')
    {
      //YOUR SOME LOGIC IF ANY
      $form['#submit'] = array('custom_form_submit_handler');
    }
}

function custom_form_submit_handler($form, $form_state)
{
//YOUR SOME LOGIC IF ANY
   $form_state['redirect'] = 'your_url';
}


How to query the database to create a report based on user input variables in a form? I am creating an example report of user data based on selection criteria selected in a form. I can create the form variables, and I can redirect the user to the report output page, but how do I include the selection criteria variables in the redirect? Here is my module code:

<?php
/**
 * @file
 * Example form module that creates a users report.
 */

/**
 * Implements hook_menu().
 */
function example_form_menu() {
  $items = array();
  $items['example-form'] = array(
    'title' => 'Example Form',
    'description' => 'Provides search criteria for the Users report',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('example_form_create_form'),
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['example-form-output'] = array(
    'title' => 'Report output',
    'description' => 'Output page for Users report',
    'page callback' => 'example_form_output_page',
    'access arguments' => array('access content'),
  );
  return $items;
}

/**
 * Creates a form.
 */
function example_form_create_form($form, &$form_submit) {
  $form['title'] = array(
    '#title' => t('User'),
    '#type' => 'textfield',
    '#description' => 'Search for a User.',
  );

  $form['user-date-created-comparison'] = array(
    '#title' => t('Creation Date'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(
      array(
        t('is greater than:'),
        t('is less than:'),
        t('is equal to:'),
      )
    ),
    '#empty_option' => '',
  );

  $form['user-created-date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'm/d/Y',
    '#date_label_position' => 'within',
  );

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

  return $form;
}

/**
 * Implements hook_form_alter().
 */
function example_form_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == "example_form_create_form") {
    $form['submit']['#submit'][] = 'example_form_redirect_handler';
  }
}

/**
 * Attaches the redirect to the submitted form.
 */
function example_form_redirect_handler($form, &$form_state) {

  $form_state['redirect'] = 'example-form-output';
}

/**
 * Creates the report output page.
 */
function example_form_output_page() {

  // Here is where I am stuck. How do I access the form variables?

  // Call db_select()

  $html = "
Report Output:
";

  // Display users, roles, creation date, etc. based on the search
  // criteria supplied in the form.

  return $html;
}

I think you pass some arguments when you redirect the page to another page.
You can pass arguments like this way..

$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

Or You also can use drupal_goto() like this

drupal_goto('your_url', array('query'=>array(
'variable_name1'=>'variable_value1',
'variable_name2'=>'variable_value2',
'variable_name3'=>'variable_value3',
...... ...
)));

You can check below links for more information.
https://api.drupal.org/api/drupal/includes!form.inc/function/drupal_redirect_form/7
https://www.drupal.org/node/291680
https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_goto/7

Note : Ignore to use this options.
And last options is $_SESSION variable. you can store your data in session and after  getting data from session in your destination page you unset that particular  session data.


How do I change status from "Pending" to "Completed"? Ubercart is install without any payment gateway. The workflow is to take user orders via out website and payments are handled offline. Once we received payment and shipped the product, we'd like to mark the order as Completed.

Here is the doc:

  When a customer moves from the checkout form to the review order page, a new order is created with their information in the default
  status for the in_checkout state. (By default, this is "In checkout.")
  When a customer completes checkout, the order gets moved from the default in_checkout status to the default status for the post_checkout
  state. (By default, this is "Pending.")
  The rest happens manually by order administrators, but the other two default statuses are "Processing" and "Completed." Processing is
  actually just another status in the post_checkout state while
  Completed is the default status for the completed state.

However, I don't see a status dropdown list or similar UI element for changing an order's status when editing an existing order:

  http://shop.example.com/admin/store/orders/100001/edit

How can I change the status from Pending to Completed?

Under the drupal 7version of Ubercart 3, order status would be changed using the dropdown found under

http://shop.example.com/admin/store/orders/100001/view


Poll Rules integration How can I integrate core poll module with rules?

I found the advpoll module but it is still in dev version and throws errors everywhere.

I am looking to simply trigger a rule after user votes on a poll.

Are there any alternatives to achieve the same functionality?

It turned out to be fairly easy to do through custom module:

MYMODULE.module

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'poll_view_voting':
      $form['vote']['#submit'][] = 'MYMODULE_poll_view_voting_submit';
      break;
  }
}

/**
 * Submit handler for poll_view_voting form.
 */
function MYMODULE_poll_view_voting_submit($form, &$form_state) {
  // Invoke our custom rule and pass the loaded node object as an argument.
  rules_invoke_event('MYMODULE_poll_vote', node_load($form['#node']->nid));
}

MYMODULE.rules.inc

/**
 * Implements hook_rules_event_info().
 */
function MYMODULE_rules_event_info() {
  return array(
    'MYMODULE_poll_vote' => array(
      'label' => t('User casts a poll vote'),
      'help' => t('Triggers when users are casting votes on polls.'),
      'group' => t('MYMODULE HUMAN NAME'),
      'variables' => array(
        'poll' => array(
          'type' => 'node',
          'label' => t('Poll node'),
          'description' => t('Voted poll node.'),
        ),
      ),
    ),
  );
}


Google Analytics configuration setting for Drupal multisite (domain and submain) I am working on a Drupal mulsite project (using single database) and using Google Analytics module for this.

I have follow the below steps for GA configuration:

Created a domain name example1.com and a sub-domain name example2.com.
Create an account on GA and create property for both of this domain name in GA account. Both property give me two different Tracking ID (same as below screenshot).

Into the configuration setting of GA from drupal admin section I have added Web Property ID of example1.com and into domain setting added both the domain name example1.com and example2.com into the section of List of top-level domains (a same as attached screenshot).

Now this configuration is only working for emample1.com, not for example2.com. So can anyone please tell me how can I use Web Property ID of domain exmaple2.php to get the result?

As Kiamlaluno states, this is likely caused by the fact that the module only allows one UA, while you are trying to track two domains. According to the GA module documentation it can be overridden using code like this in settings.php:

<?php
// Override Google Analytics Web Property ID per hostname.
// Hostnames need to be lower-case!
switch ($_SERVER['HTTP_HOST']) {
  case 'www.example.com':
  case 'www.example.net':
  case 'forum.example.net':
    $conf['googleanalytics_account'] = 'UA-123456-2';
    break;

  case 'www.example.org':
    $conf['googleanalytics_account'] = 'UA-123456-3';
    break;

  default:
    $conf['googleanalytics_account'] = 'UA-123456-1';
}
?>

Documentation can be found here


Access input format based on user role I have the Developer user role which should only access the developer_html input format. I am trying to grant the necessary permission with user_role_grant_permissions().

I got this piece of code here
and also tried to edit according to my requirement, but failed.

function filter_update_7008() {
  // Build the list of permissions to grant.
  $permissions = array();
  foreach (filter_formats() as $format_id => $format) {
    if ($permission = filter_permission_name($format)) {
      $permissions[] = $permission;
    }
  }

  // Grant text format permissions to all roles that can 'administer filters'.
  // Albeit anonymous users *should not* have the permission, we cannot presume
  // that they do not or must not.
  if ($roles = user_roles(FALSE, 'administer filters')) {
    foreach ($roles as $rid => $name) {
      user_role_grant_permissions($rid, $permissions);
    }
  }
}

The general solution for cases like this, where you want to export an input format, a role, and a permission associated to that role is using the Features module. Selecting what you want to export on admin/structure/features/create, the module will create a feature: a module that (once installed) will make available what exported.

If you don't want to use the Features module, you can create a module that:

Creates the Developer role if it doesn't exist
Creates the input format if it doesn't exist
Creates the permission to use that input format if it doesn't exists
Assigns the permission to use that input format to the Developer role

Assuming that the role and the input format already exist in the site, the code is simply the following.

if ($format = filter_format_load('developer_html')) {
  if ($permission = filter_permission_name($format)) {
    if ($role = user_role_load_by_name('developer')) {
      user_role_grant_permissions($role->rid, $permission);
    }
  }
}

As to where to use this code, you have two possibilities:

hook_install()
hook_enable()

hook_enable() is what the Forum module uses to create the forum vocabulary and the "taxonomy_forums" field it uses (see forum_enable()). I would use this hook if the module requires something to be set/present before it runs; differently from hook_install(), it has also the pro of not requiring a hook_update_N() to be added for those users who update the module, since hook_install() runs only during installation, while hook_enable() runs every time the module is enabled.


Is there a central document store in Drupal 6 or a module that does? I have a content type in Drupal 6 that consists of 3 main fields, each allows for the upload of unlimited files, which I have restricted to being PDF or DOC based formats. Lets say there will 100 pieces of content based on this type. Whilst most of the uploads made, may well be unique, the customer has identified that there are a few docs, that may need to be uploaded to more than one piece of content.

This led on to the question regarding if there is a central document store of some kind in Drupal (especially 6 in this case). Such a tool would mean that files would only need to be uploaded once but referenced many times from various pieces of content.

Does anyone have any solutions to this scenario?

Sounds like the FileField Sources module is exactly what you're looking for.

  FileField Sources is an extension to the FileField module. The
  FileField module lets you upload files from your computer through a
  CCK field. The FileField Sources module expands on this ability by
  allowing you to select new or existing files through additional means,
  including:

  Re-use files by an auto-complete textfield Attach server-side files
  uploaded via FTP Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only) Select
  existing files through the IMCE file browser


Menu doesnt appear on custom 'not found' page On my site I have configured things so that the home page will appear if the URL doesnt exist.
(ie in admin/settings/error-reporting I set a replacement page for the 404 page.)

The problem is that the menu doesnt appear, so if a user lands here he cant use the site properly.

My menu is the 'primary menu' and has been placed in the left sidebar. I dont have any special setting for this block - eg no page 'includes' or 'excludes'.

To help me debug can anyone tell me if this is the expected behaviour or any suggestions for what might have gone wrong?

I'm using Drupal 6.

Drupal doesn't render the region of your theme that your primary menu is in; there's a module to change this behavior:

  On 404 Not Found error pages, Drupal will skip rendering of several
  pieces of your website for performance reasons. Some of these include:

  The "Left" and "Right" regions of your theme.
  The "Primary links" block and any other menu links block.*
  The Primary links and Secondary links of your theme.*

  *Unless you have configured a "Default 404 (not found) page" on
  admin/settings/error-reporting.

From 404 Blocks module description.


Dynamic Content Type? (field appears based on previous taxonomy choice) I want to show/hide a field based on a taxonomy choice (in the content admin side of things).

Though having this field attached to every item of this content type does add overhead; I suspect it contributes to the easiest solution for a dynamic field.

I like the idea of dynamic fields, where only certain instances of an entity would have/need them, however, this seems like it could be quite an undertaking. (or my Drupal imagination is lacking today)

Try out the Conditional Fields module.

Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.
Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.


How do I alter image field code without hacking core? I need to change the style of the title in image field to be a text area rather than a text field. I can achieve this by hacking core in the following way:

image.field.inc line 410

$element['title'] = array(
    '#type' => 'textarea',
    '#title' => t('Title'),
    '#default_value' => isset($item['title']) ? $item['title'] : '',
    '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'),
    '#maxlength' => variable_get('image_title_length', 500),
    '#weight' => -1,
    '#access' => (bool) $item['fid'] && $settings['title_field'],
  );

// Change '#type' => 'textarea'  to '#type' => 'textfield'

I don't though, want to hack core.
How can I create a preprocess function to allow me to do this via my template.php.

You won't (easily) be able to use a preprocess function to do this as the element is generated by a form.

You could use a non-generic hook_form_alter() implementation to do this on a single form, but the best way would be to write a small custom module and implementhook_field_widget_form_alter() to override the element.

The alt and title fields (along with some others) are only added in a #process function of each image element (image_field_widget_process()), so you'll need to add your own #process function to run after that one, and alter the field type in there.

The following code is tested and seems to work well (including playing nicely with the AJAX functionality on the image field):

function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // If this is an image field type
  if ($context['field']['type'] == 'image') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element
      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
  // Change the title field to a textarea
  $element['title']['#type'] = 'textarea';

  // Return the altered element
  return $element;
}

It produces results like this:

It might be worth bearing in mind that the maximum size of the title column is set in the database, so you won't be able to go any higher than 1024 characters.


How do I programmatically create an entity reference in hook_entity_info()? Is there a way to create an entity reference in hook_entity_info? I was hoping for something like the following.

'entity keys' => array(
  'id' => 'id',
  'store_ref_id' => 'store_ref_id',
),

I have a content type store with its ID, and a new entity_type product. I would like to have a field in the new entity referenced to content type.

How can I do this?

Would it be better to re-use the already created field, which is used as reference between content types?

You can attach this field like any other:

function MY_MODULE_install() {
  // Create a field for company reference to be used by various entities
  $field = array(
    'field_name' => 'company_reference',
    'type' => 'entityreference',
    'settings' => array(
      'target_type' => 'company',
      'handler_settings' => array('target_bundles' => NULL),
    ),
    'cardinality' => 1,
    'translatable' => FALSE,
  );
  field_create_field($field);

  // Attach the company reference field to employee instance
  $instance = array(
    'field_name' => 'company_reference',
    'entity_type' => 'employee',
    'bundle' => 'employee',
    'label' => 'Company',
    'required' => false,
    'widget' => array(
      'type' => 'options_select'
    ),
    'settings' => array(
      'target_type' => 'company',
      'handler_settings' => array('target_bundles' => NULL),
    ),
    'display' => array(
      'default' => array('label' => 'inline', 'type' => 'entityreference_label'),
    ),
  );
  field_create_instance($instance);
}

Code sample taken from this more comprehensive manual.


Default values for panelizer and fieldable panel panes I have a template being applied to a node with a few different fieldable panel panes on it. I can create a new piece of content and it's page will load with the template applied and all of the FPP's right where they should be.

Say I make 10 pieces of content and they all have that same template. If I go to one of them and add something to an FPP on it and then save as custom that FPP will be modified the same way on all 10 pages. If I use the inline editor and remove the panel with content, save as custom, and then add that panel back it will be empty.

If I have a blank panels template and go to all 10 pages one at a time and add the FPPs to them and save them each as custom then the FPPs will stay unique.

I need to be able to load the complete template with the content panes already there but have them all be empty when the page is initially made.

Is there anyway to assign a panel a default value of nothing?

The methods hook_entity_insert() / hook_entity_update() don't check whether an entity has dedicated panelizer settings or not and just always saves the panelizer object found for it. Which can be the defaults of course.
The attached patch looks worse than it actually is. It basically introduces the property entity_custom_panelizer which indicates if a panelizer setting is dedicated to the entity or not.
And the hooks hook_entity_insert() / hook_entity_update() only save the settings into the panelizer_entity if the flag is set.
I really hope I didn't miss something but first smoke-tests look promising.


date format in database of quiz module I make a quiz with quiz module and the start date is 1/8/2013 4:30 and the close time is 10/8/2013 4:30.
In the database it stored as this=>

1375315200(quiz open)
1376092800(quiz close)

which one is year, month and day?

Use PHP's date() function.

Example:

echo date('m/d/Y', 1299446702);

Check Unix Timestamp Conversion Tools online


Fatal error: Class 'Drush\Log\Logger' not found Hi I'm getting this Drush error no matter which command I try.

Fatal error: Class 'Drush\Log\Logger' not found

How can I fix it?
I haven't been able to find other users reporting the same issue. I'm using Drush 8.

I had the exact same problem after updating core with drush (installed with composer). This is not something you should do if drupal is installed in the root directory, I've now learned. Reinstalling drush fixed the issue for me.

composer require drush/drush

Next step, I guess if we want to avoid this in the future, is to either move drupal to a subdirectory (as a dependency) or uninstall drush as a composer package and install it globally instead (the old fashioned way).


Ubercart - moving uc_order-customer.tpl.php to my theme folder makes emails sent twice Ive copied uc_order.tpl.php to my them folder as well as uc_order-customer.tpl.php which ive used to remove a few fields from the customer's notification email.

The problem is that now the same email notification is being sent twice at the same time, to the same email address.

If I remove the files from the theme folder, the problem goes away, but of course I need to modify the template and i wont want to hack core.

Thanks

Updating to the latest module version fixed this.


How to obtain a list of the submodules of a module using Drush? I want obtain trough drush a list of the availables submodules that comes inside a module.

So far this is what I have achieved:

drush pmi views_*

I obtain a detailed info for all the modules and themes starting with views in his name. (views_ui, views_bulk_operation, etc)

drush pml views | grep views_

In GNU/Linux systems I obtain a list of availables modules and themes starting with views_ in his name (views_ui, views_bulk_operation, etc)

But I can't obtain only the submodules of a module.

Edit: I'm using Drush 5.10.

This information is available via the pm-projectinfo command:

$ drush pm-projectinfo views
 Name         :  Views (views)
 Version      :  7.x-3.13
 Extensions   :  views
                 views_test
                 views_ui

This command is available in Drush 8, and was first introduced in this PR.  It is also available in Drush Extras for older versions of Drush.


How can I make a page with only blocks but without node content ? I simply removed the $content variable from the tpl.php file and placed only some blocks in several regions. Then the blocks are displayed fine but the message "Page not found" appears. So I suppose this is not the right way to achieve this.I know that for example Views and Panel can make pages with paths defined by their own without node content. But can I still have a page which has its own path and with only blocks but no node content without using Views or Panel?

You can use the the Empty Page module to allow you to have pages solely for placing blocks.

  The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks.


Creating nodes and sub-nodes from database table For example I have a database table defined from the following SQL.

CREATE TABLE IF NOT EXISTS `mytable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `base_id` int(11) NOT NULL,
  `page_type` smallint(4) NOT NULL,
  `page_title` varchar(50) NOT NULL,
  `page_content` text NOT NULL,
  `previous_id` int(11) NOT NULL,
  `next_positive_id` int(11) NOT NULL,
  `next_negative_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

I need to create nodes/content by using records inside that table. For example I have a base node, its id is 1. I get its title and its content from mytable. Inside this page I ask a question: "Do you like cats?" If the user selects yes, I send him to sub-node. I get sub-node address, title and content from mytable. You can see the flow like the below. Until the latest sub-node I give options to user. He selects YES or NO and sees relevant content/sub-node.

How can I make it with a Drupal 7 site?
I have another Drupal website but I have never used such complex flow. I created nodes and used contributed modules. Is it so hard to make this flow? Which modules should I use to setup such hierarchy and content management?

One solution would be to create a new content-type, let's call it Question-Page and the install Entity Reference, which provides a field type that can reference other nodes. Then you could add three new fields for previous_id, next_positive_id and next_negative_id.

To import the data from your table I think you could use the Feeds module. First create one importer that will create the actual nodes. Second an importer that will update each node and set the node reference fields.

First importer that will only create all nodes.

Second importer, that will setup the reference fields.


Show closed form as read only form I'm working on a Drupal 8 project where I need to show closed webforms as read-only form (without submit button and possibility to answer them), but Webform behaviour doesn't fit my need, as it only display a message "Sorry...This form is closed to new submissions." without displaying the webform.

Is their any way/hook that will allow me to display these closed webform?

You would need to not close the form but use hook_webform_submission_form_alter() to change all elemnts to be readonly and hide the submit buttons.


Show the value of a node-form field inside an AJAX field added via hook_form_alter() I have created a simple content type "reservation" with an integer field called "field_km" with a default value of 50.
On the node creation form, I want to have a markup field showing the value of the "field_km" field.
So, I have created a simple module with the following code:

/**
 * @file
 * Drupal Module : myresa
 * Adds custom code specific to this Drupal 7 site.
 */

function myresa_form_reservation_node_form_alter(&$form, &$form_state, $form_id) {
  $form[‘box’] = array(
    ‘#type’ => ‘markup’,
    ‘#prefix’ => ‘’,
    ‘#suffix’ => ‘’,
    ‘#markup’ => ‘Price not computed',
  );

  $form[‘mybtn’] = array(
    ‘#type’ => ‘button’,
    ‘#id’ => ‘mybtn’,
    ‘#ajax’ => array(
      ‘callback’ => ‘myresa_callback’,
      ‘wrapper’ => ‘box’,
      ‘name’ => ‘mybtn1’,
    ),
    ‘#value’ => t(‘Compute the price’),
  );
}

function myresa_callback($form, $form_state) {
  $element = $form[‘box’] ;
  $element[‘#markup’] = «The price for » . $form_element[‘field_km’][‘#default_value’] . » km is 35 euros» ;
  return $element ;
}

The form shows the 'box' markup, the button, and when clicked the button activates the callback and shows the wanted text, but not the value of 'field_km'.
It is probably a simple syntax mistake, but it beats me.

function myresa_callback($form, $form_state) {
  $element = $form[‘box’] ;
  $element[‘#markup’] = «The price for » . $form_element

No wonder this doesn't work, where does $form_element come from? Also fields tend to be structured like $form[field name][$node->language][columname] (the latter being value in your case IMO)