How do I free the memory used from node_load()? I am using code similar to the following one.

for ($i = 0; $i < 1000000; $i++) {
   $nid = get_node_id($i);
   $node = node_load($nid);
   $data = [
     $node->field_1,
     $node->field_3,
     ...
   ];
   save_to_database($data);

   echo round(memory_get_usage() / 1024 / 1024, 2) . ' MB'. PHP_EOL;
}

Every time a loop is completed, the used memory is increased. For example, after the first loop, the used memory is 110 MB, and after the third loop is 230 MB.

How do I avoid the used memory keep increasing?

It happens because node_load(), as every Drupal function that loads entities from the database, stores in memory the loaded entity. If you want to avoid that happens, you can use code similar to the following one.

for ($i = 0; $i < 1000000; $i++) {
  $nid = get_node_id($i);
  $node = entity_load('node', array($nid), array(), TRUE);
  $data = [
    $node->field_1,
    $node->field_3,
  ];
  save_to_database($data);
}

The last argument of entity_load() is telling Drupal not to store in memory cache the previously loaded entity.

This is what happens with the default entity controller implemented from Drupal, DrupalDefaultEntityController, which uses the following code for DrupalDefaultEntityController::resetCache().

public function resetCache(array $ids = NULL) {
  if (isset($ids)) {
    foreach ($ids as $id) {
      unset($this->entityCache[$id]);
    }
  }
  else {
    $this->entityCache = array();
  }
}


Edit a form retrieved using FormBuilder::getForm() I found out how to get a node creation form, but I want to display and modify it (e.g. delete some fields I don't need).

This is my code.

public function buildForm(array $form, FormStateInterface $form_state) {
  $entity = \Drupal::entityManager()->getStorage('node')->create(array(
    'type' => node_type_load('friterie')->id(),
  ));
  // OPTIONAL - Set default values for node fields
  // $entity->set('field_machine_name', "value");
  $node_create_form = \Drupal::service('entity.form_builder')->getForm($entity);

  // I can display it with this method, but I don't know how to delete
  // some fields.
  $form['friterie'] = array(
    '#type' => 'markup',
    '#markup' => render($node_create_form),
    '#prefix' => '
',
    '#suffix' => '
'
  );
  return $form;
}

I see two approaches here:

You will have to use "hook_form_alter", or a more strict form alter (for example: hook_form_FORM_ID_alter()). You can remove any elements there (calling from you .module file).
When you get back your form object ($node_create_form) which will be rendered later on, you could make changes on that specific object witt it's public methods! Just dpm, or kint the object (with devel module enabled), and you will able the find the right method to alter the form elements you are about to render.

Side note: I highly discourage you from using "\Drupal::..." static service calls. FormBase classes are implementing the ContainerInjectionInterface, which means, in public static create function you can pass the services you need. Read more on this here!


How can you filter an integer column by "Starts with"? I have a view, and I want the users to be able to filter on an Integer field.  String fields allow for filtering by 'Starts with'.  I would like to do the same but with an integer.

If the user enters "10" it would match 100, 1010, etc, but not 210.

You can do this with a combine fields filter.

You first need to include the field you want to filter on.
Once the field is in you add the filter combine fields filter and set it to exposed.
Change the operator to "begins with" and select the integer field.

Save the changes and you should have the filtering option with the begins with option on an iteger field.


Block in Utility menu top only shows on home page heres my site coonvalleytel.com/drupal

I made a block with 3 pictures that are links to youtube, twiter and facebook.  But they will only show when you are on the home page.  Do you guys have any ideas for getting it to show for every page?

Please tell us about the view you have defined. What is the path, the filters, etc that have been included. The pages your view shows on are dependent upon the address or block settings you have defined for the view.


Edit a config variable of a custom module in controller Is it possible to edit/create a config variable of a module in a controller created in the same module?

For example:
module_name/src/Controller/MyController.php:

class MyController extends ControllerBase {

    public function x($y) {
        $config = \Drupal::config('module_name.settings');
        $config->set('var1', $y)->save();
    }
}

Update:

module_name.module:

function module_name_page_attachments(array &$page) {
  $config = \Drupal::config('module_name.settings');
  var_dump($config->get('var1'));
}

module_name/config/install/module_name.settings.yml:

var1: 0

module_name/src/Form/moduleNameSettings.php:

class moduleNameSettings extends ConfigFormBase {

    protected function getEditableConfigNames() {
        return [
            'module_name.settings',
        ];
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        parent::submitForm($form, $form_state);
        $config = \Drupal::config('module_name.settings');

        $this->config('module_name.settings')
            ->set('var1', $config->get('var1'))
            ->save();
    }

With the ConfigFormBase, you need to implement the editableConfigNames() method.  E.g.

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'example.settings',
    ];
  }

In general, you need to get the editable version of the config file to change it.  ConfigFormBase (well actually, ConfigFormBaseTraits) will only return the editable config is you implement the above method.

For reference, here's how you could do this without the ConfForm logic.

$config = \Drupal::service('config.factory')->getEditable('example.settings');
$config->set('message', 'Hi')->save();

See the documents for details.

Since you are expanding ConfigFormBase, you should be able to use:

$config = $this->configFactory()->getEditable('example.settings');

To get the editable version.


Nothing is saved in Account settings When I'm at this page "admin/config/people/accounts" I can't change anything of the settings. So I uncheck a checkbox or typ another value in an input. When I click the save button, the page reloads but the settings go back to the values before.

Anyone who knows the problem? Other pages does save my settings, it only appears on the "admin/config/people/accounts".

I use Drupal 8.

Thanks!

In modules check for the hook_user_admin_settings_alter, check the form action and change it for the modules implementing those function

$form['#submit'][] = 'module_user_admin_settings_submit';

For reference sample forgot_username module

Instead of this
$form['actions']['submit']['#submit'][] = 'forgot_username_user_admin_settings_submit';,

use this
$form['#submit'][] = 'forgot_username_user_admin_settings_submit';

In my case, forgot_username module breaks the account savings.

Reference : https://www.drupal.org/project/private_message/issues/2905184
Patch : https://www.drupal.org/files/issues/private_message-admin_settings_submit_handler_beta18-2905184-3.patch


Create a new revisions only at the time of specific state transition I am using Revisioning and Workflow module along with Drupal 6 to create new states of the node and revisions.Currently if I select 'New revision in draft, pending moderation (requires "Create new revision")' under workflow settings it will create a new revision only when a node is published.But I want it other way.I want to create a new revision only at aspecific state change of my choice.

For e.g. The node is in 'Finally Submitted' state and it is transitioned to 'Moderation' state. At this transition I want to a new revision to be created otherwise not.

How is that achievable?

I would look into using Rules, You can have something like the below:

Event: Workflow state has changed
If: Workflow state is x (choose your state)
DO: Create a new pending revision of the node


Drupal 8 Webform - Pass submitted value from one webforms to another I have two webforms on my Drupal 8 website. When a user submits the first webform, I have the confirmation redirect set to a second webform. I would like to populate one of the fields in the second webform with one of the submitted values from the first form. I have it set up as two separate webforms as some users will by-pass the first form and go directly to the second webform where they can manually enter the content into the field I need populated. Any idea how I can achieve this?

Thanks

F

Ok I figured it out - for anyone else who comes across this question.

In the first Webform, I set the Confirmation URL to:

/form/my-form2?value=[webform_submission:values:element_key]

I've bolded the elements in the URL that you will need to adjust for your webforms.

This will result in redirecting the user from my first Webform to the second Webform (which is at the URL www.mydomain.com/form/my-form2) when they click the submit button. It will append ?value=[the value from the webform field] to the end of the URL.

Then in the second form in the field where I want this value to go, I have set the Default value for this field as

[current-page:query:value]

The word 'value' in the above can be anything, but it must match the id used in the URL from the first form.

And hey presto - it works!

F


How can i add or set more email tokens in my drupal 6 site I would like to add more email token variables in my Drupal 6 site.I have found some of the variables like !username, !temp, !site, !password, !uri, !uri_brief.Is there any way by which i could add more tokens and assign these token variables in my custom module.Could I accomplish this by using some contributed module or programatically.Hope someone could help me with this.

i guess you want more tokens in the users settings page admin/user/settings (D6), according the format of your token (!username)

This page is a bit special because it is a core feature.
cf User settings

Token module provides more tokens like [my-token] but this cannot be applied in the admin/user/settings

If you want more tokens on the users settings, i suggest to use a custom rule (fire on user's creation) with the rules module


Search for product displays based on info from products in Commerce I have a website with various articles of clothing for sale. Here's how I have it set up:

Product Display content items:

Mens V-Neck Tshirt
Mens Tank Top Tshirt
Womens Tshirt
Childrens Tshirt

Product content items (in Commerce):

Mens V-Neck Tshirt - Red - Large
Mens V-Neck Tshirt - Blue - Large
Mens Tank Top Tshirt - Green - Small

etc...

Colors (Red, Blue, Green) and sizes (Large, Small, etc) are set up as Select-List fields with the Enable this field to function as an attribute field on Add to Cart forms option enabled.

I need to allow my shoppers to search for shirts that have Red as an available color, or that have Small as an available size. So if they searched for shirts that are Red and Small, they would receive no results based on the product list above, but if they search for Green and Small, they would see the Mens Tank Top Tshirt product display item in their search results.

How can I set this up? With Views/exposed filters, perhaps? Or...?

Thanks!

Use Commerce Search API module. Basically you are gonna have to set up Facets to achieve what you want.

This screen cast here walks you through on which modules you have to enable and how to tweak your configurations.


How do I upload an image to the public:// directory? Is it possible to upload the picture and set it as user picture?

User picture can be set via $user->picture = $file->fid; user_save($user);but how do I upload the file from a URL to the public:// directory?

If you want to create the code for saving the image yourself, you could do

$response = drupal_http_request($url_image);

if ($response->code == 200){
  $file = file_save_data($response->data, 'public://' . 'foldername/' . $filename);
}

And in $file->fid you'll find the fid you need.


adding adwords tracking to a Click instead of a page load using goog_report_conversion I am using the simple subscription module to subscribe users to a newsletter and wish to track clicks of subscribers.  Is there an easy way to call the goog_report_conversion() function when someone clicks on the subscribe button? I don't see any configuration for this with the simple subscription module.

General advice: don't use "simple" modules for non-simple tasks.

No easy way here, you need to inject your JavaScript code, and attach additional behavior to that button. Worse, you would need to make sure there is enough time for function to process. My colleagues use thank you page if feasible for that very reason - browser will do it's best to minimize time between button click and page load. On thank you page that is not an issue.


How to add css files based on breakpoint in library? We have the following mytheme.breakpoints.yml file and a simple library mylibrary that is added through our mytheme. Within the mylibrary there are two libraries, one that is optimized for desktop small and another for mobile breakpoints.

How would I add the mobile css file only for when the browser's breakpoint is less than 756px, but load desktop small breakpoint when browser's breakpoint is greater than 756px?

mytheme.breakpoints.yml

mytheme.mobile
  label: mobile
  mediaQuery: 'all and (max-width: 756px)'
  weight: 1
  multipliers:
    - 1x
mytheme.desktopSmall
  label: desktop small
  mediaQuery: 'all and (min-width: 756px)'
  weight: 1
  multipliers:
    - 1x

mytheme.libraries.yml

mylibrary:
  version: 1.0
  css:
    theme:
      css/some/path/desktop-small.min.css: { /* load only for min width > 756px*/ }
      css/some/path/mobile.min.css: { /* load only for max width < 756px*/ }

Adding Use Theme Breakpoints as Media Queries for Theme CSS Libraries for reference.

Here is the solution I found.

mytheme.libraries.yml

mylibrary:
  version: 1.0
  css:
    theme:
      css/some/path/desktop-small.min.css: { media: all and (min-width: 756px) }
      css/some/path/mobile.min.css: { media: all and (max-width: 755px) }


Drush bootstrap fail - wrong MySQL username drush sql-connect produces valid, working MySQL credentials:

  mysql --user=drupaluser --password= --database=core_20161101
  --host=127.0.0.1 --port=33067

So does drush status:

  Database driver        :  mysql
  Database hostname      :  127.0.0.1
  Database port          :  33067
  Database username      :  drupaluser
  Database name          :  core_20161101

However drush -d uinf admin and anything else that needs to read the database fails with:

  [...] sql-query: SELECT 1; [0.35 sec, 4.88 MB]
  [notice] Executing: mysql
  --defaults-extra-file=/private/tmp/drush_dZeMQb --database=core_20161101 --host=127.0.0.1 --port=33067 --silent  < /private/tmp/drush_Tu2o2g   ERROR 1045 (28000): Access denied for user
  'root'@'localhost' (using password: YES) Bootstrap to phase 1. [0.37
  sec, 4.88 MB]
  [bootstrap] Bootstrap to phase 6. [0.54 sec, 6.68 MB]
  [bootstrap] Bootstrap to phase 5. [0.54 sec, 6.68 MB]
  [bootstrap] Command user-information needs a higher bootstrap level to
  run - you will need to invoke drush from a more functional Drupal
  environment to run this command. [0.54 sec, 6.68 MB]
  [error] The drush command 'uinf admin' could not be executed. [0.54
  sec, 6.68 MB]
  [error] Drush was not able to start (bootstrap) the Drupal database.
  [...]

Note the username is wrong, root@localhost, not drupaluser@127.0.0.1.

Any ideas why it would be switching to the wrong username?

Versions:
Acquia Dev Desktop 2 (built Sep 5 2016)
PHP 5.5.33 (as set by Dev Desktop)
Drush 8.0.5
Mac OS 10.11.6

You don't happen to have a ~/.my.cnf file (which sets the user to root)? MySQL will read that file after the file specified by --defaults-extra-file, and "If multiple instances of a given option are found, the last instance takes precedence".


Json api create comments I am using the JSON API module and I would like to create a comment. I was able to create nodes based on the documentation found here, but I can't figure out how to create comments.

How can I add a comment using that module? I managed to do it through the default REST API module.

It follows the same pattern in the POST request with relationships section of the docs you linked to.

Your endpoint will be /jsonapi/comment/$MY_COMMENT_TYPE.
Your data payload will need to contain both the data property (the  comment's properties) and relationships property (which will contain the comment's author & the entity reference commented on). To get a more concrete example of your data payload, perform a GET /jsonapi/comment/$MY_COMMENT_TYPE to see examples of existing comments.


eCommerce : fields vs attributes? From the docs :

  Products variations can have attributes and other kinds of fields. Going back to our t-shirt analogy from above, if our t-shirts come in sizes and colors, perhaps the product variation should have an image field so you can upload a picture of a small red shirt. These kinds of non-attribute fields are loaded dynamically when variations are chosen.

What is the difference of purpose and meaning of "non-attribute fields" AND attributes ?
How are they different and similar ?

The way I think about it is in terms of sku numbers (or manufacturing part number/catalog number.) If a single product is available in multiple sizes (1 mg, 50 mg, 1 gm), each one will have its own unique sku. Those sizes are the variation attributes. But then I may also want to add on a non-attribute field like an image or a packaging/shipping surcharge (for a larger size). That data is specific to the product variation but isn't related to the sku.

Using the t-shirt analogy, if both size and color are attributes, then you might have the following unique variations:

TS_SM_01: small, blue t-shirt
TS_MD_01: medium, blue t-shirt
TS_LG_01: large, blue t-shirt
TS_SM_02: small, red t-shirt
TS_LG_02: large, red t-shirt
TS_SM_03: small, green t-shirt
TS_MD_03: medium, green t-shirt
TS_LG_03: large, green t-shirt

If I add on a field for an image or a field for some sort of customization, those new "non-attribute" fields do not cause me to create a whole new set of product variation sku numbers.


Get access to node titles and nid's only there are two content types on my site: Projects and Employees. Employees has a user reference field, Projects have several node reference fields to Employees (according to different project roles). I grant rights to users with Node access user reference and Node access node reference modules so they can view and edit only the nodes they are referenced to (either directly or indirectly).
Certain referenced users (project managers) should be able to add other Employees in Project nodes but in the same time they must not see their personal data. Therefore they haven't got any referencable Employee nodes.
Would it be possible to grant access to the node titles (and nid's for referencing) only and hide other fields?

Yes you can, with  field_permissions module  you can set permissions according to the fields.


Remove form elements with ajax I have made a form with form loop as I am setting the $form_state['number'] for the fields count.

I want to remove a full row after clicking on remove button in front of row by taking row_id. So I want to ask is there any way to pass id of row in submit function of remove button or check which button pressed and fetching id of that button in submit function.

 for ($i = 1; $i <= $form_state['number']; $i++) {
    $form['myform'][$i]['email'] = array(
        '#type' => 'textfield',
        '#size' => 18,
        '#autocomplete_path' => 'mypath',
        '#prefix' => '
',
    );
    $form['myform'][$i]['roles'] = array(
        '#type' => 'select',
        '#options' => array('' => '', 'master' => 'master', 'student' => 'student'),
    );
     $form['oldfeedbackmarkup'][$i]['remove'] = array(
       '#type' => 'submit',
       '#value' => t('Remove'),
       '#submit' => array('mysubmit_button'),
       '#ajax' => array(
              'wrapper' => 'myform_wrapper',
              'callback' => 'submit_by_ajax',
        ),
        '#prefix' => '
',
        '#suffix' => '

',
    );
}

It's actually easier than you think :)

You can access a $form_state['triggering_element'] in your ajax callback function.

Something like this:

function my_ajax_callback($form, $form_state) {
  $ps = &$form_state['triggering_element']['#parents'];
  $k = $ps[2]; // field collection row number
  $collection = $form[$ps[0]][$ps[1]][$ps[2]];
  $element = $ps[3];
  ...

that was the snippet to access a changed textfield inside a field collection with multiple rows. Just adopt it for your particular form structure.


how to render a template inside a template? I have entity Car which has a node reference of another entity: Review

Car has a custom .tpl file node--car.tpl.php and reviews have there own .tpl files "node--reviews.tpl.php"

when i try to render the reviews of the Car inside the node--car.tpl.php the reviews does not render using their own .tpl files,

i am using render() drupal function

can someone explain me why?

EDIT:

Heres the code which fetches the reviews:

function mymodule_get_reviews( $nid, $full = false ) {
    $field = 'field_car_reference';
    $sql_query = 'SELECT DISTINCT entity_id AS reference FROM {field_data_' . $field . '} WHERE ' . $field . '_nid IS NOT NULL
        AND ' . $field . '_nid = ' . $nid;

        $queryObj = db_query( $sql_query );

        $type = 'review';
        $nodes = node_load_multiple($queryObj->fetchCol('reference'));

    $reviews = array();

        if( !empty( $nodes ) )
        {
            foreach( $nodes as $nid => $node_review )
            {
                    if( $node_review->workbench_moderation['current']->state == 'published' ) {
                        $node_review = node_show( $node_review );
                        $reviews[] = $node_review;
                    }
            }
        }
    return $reviews;
}

the function is called as:

$reviews = mymodule_get_reviews( $node->nid );
if( !empty( $reviews ) ) {
  echo render( $reviews );
}

When a template is not being applied, the first thing to always check for is the filename of the template :)

Make sure it matches the machine name of the content type.


Taking over a url and getting variables from url I have a (non drupal bound) table, that I need to display within my site.

It has information about "runs":

userID (drupal) - runID - name - distance - ... etc

I want to go to site/run/runID and display the data of that particular run.

I don't know if there is an easy way of doing it without having to create a custom module for it? I basically just need to $get the variables and display them from the database. My first concern is calling my php code when the file is loaded.

And if I need to create a module for it. How would I go about it?

Or perhaps I can use panels to put  my custom code on a page and get the url variables? Or some other module I am not thinking about...

--Update

To get started I created this little module. Now just reading the url parameter runID that is behind it...

function epicrun_menu(){
 $items['epicrun'] = array(
 'page callback' => 'epicrun_my_page',
 'title' => 'Callback',
   'type' => MENU_CALLBACK,
 'access arguments' => array('access content'),
 );
 return $items;
}

* this code (noted in the callback above) creates the
 * contents of the "epicrun" page */

function epicrun_my_page(){
 return "
This is my epicrun demo page.
";
}

I would suggest looking into the Data module. I does pretty much everything (and more) what you're describing in your request.


How would we limit the drop down for the Date's Timzone field? We are using the Date module that allows for enabling of Timezone during node edit (node/edit). We noticed that the dropdown is really long and we were wondering if there was a way to shorten the list to just say ETC, PST, UTC, GMT, etc.

We tried all the configuration setting, but could not shorten the drop down.

Current scenario:

Desired scenario:

Timezone (as an example)
 - UTC
 - PST/PDT
 - MST/MDT
 - EST/EDT
 - GMT

The Date module's field elements are supplied by the Date API module. The timezone component is supplied by its process callback date_timezone_element_process().

It triggers hook_date_timezone_process_alter() which can be evoked by a custom module to alter the options within $element['timezone']['#options'].

For example:

/**
 * Implements hook_date_timezone_process_alter().
 */
function MYMODULE_date_timezone_process_alter(&$element, &$form_state, &$context) {

  if (isset($element['timezone']['#options'])) {
    // @TODO: Supply an array filter function that filters
    // IANA TZ names that don't correspond to
    // UTC - PST/PDT - MST/MDT - EST/EDT - GMT

    // Example: Filter TZ's that are only in the Americas
    $element['timezone']['#options'] = array_filter($element['timezone']['#options'], function($key) {
      return strpos($key, 'America/') !== FALSE;
    }, ARRAY_FILTER_USE_KEY);

  }
}


Add comments to Webform submissions I'm trying to figure out allow commenting on the submissions so there can be a back and forth dialog between the user and site admin(s).

In Drupal 8 webform submissions are entities (type: webform_submission) and comments are a field.

I have created a new Comment Type (webform_submission_comment) with the "Target entity type" set to webform_submission).

How do I attach a comment field to the webform_submission entity?

Webform submissions are content entities without Field API  enabled.  Comments can only be attached to fieldable entities.  Webform submission data is not stored Field API, but your use case is a very reasonable example of why Field API could/should be enabled.  The challenge is the UX for supporting fields, and webform elements at the same time could be overwhelming.  I am not prepared to support this the core Webform module.  A dedicated webform_comment.module could be created to enable Field API and might even only support for adding comments to submissions.

You are going to have use hook_entity_type_alter() to add 'field_ui_base_route' to the WebformSubmission entity.

  If your content entity is fieldable, provide 'field_ui_base_route'
  annotation, giving the name of the route that the Manage Fields,
  Manage Display, and Manage Form Display pages from the Field UI
  module will be attached to. This is usually the bundle settings edit
  page, or an entity type settings page if there are no bundles.

-- https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/8.2.x


I get this error with my custom module, Any advice on tracking down the problem? I get this error when i select an option form a select list.

http://i.stack.imgur.com/ACmDg.png

Drupal Watchdog log Error Details

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'examplesite.field_data_field_for_date' doesn't exist: SELECT r.entity_id AS entity_id FROM {field_data_field_for_date} r WHERE (field_for_date_target_id = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 0 ) in stopsale_getcurrentsale() (line 249 of /nfs/c05/h02/mnt/examplesite.com/html/sites/all/modules/custom_apps/stopsale/stopsale.module).

http://i.stack.imgur.com/ACmDg.png

You need to create a custom field called for_date which will be represented in the database as field_data_field_for_date or remove field_data_field_for_date from the SQL query.


more than one contact form block? I have this module enabled

http://drupal.org/project/contact_form_blocks

but I only have one contact form block, which is set to global.  How would I make another contact form block?  Thank you!

Try Webform, to create many flexible forms. Here is a quote about it (from the module's project page):

  ... is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.


return message after hook_form_submit without Ajax This might seem trivial to many of you, but how can you return a form with a customized message (according to the fields) in a hook_form_submit ? Like :

   <?php
/**
 * @file
 * Pages and display.
 */
/**
 * Constantes
 */

/**
 * *************** Formulaire *******************
 */

/**
 *
 * Implements a standard form.
 */
function MY_MODULE_form($form, $form_state, $arg) {
  $form = array ();
  $form ['#type'] = 'type';
  /**
   * All the form elements
   */

  // soumission du formulaire
  $form ['submit'] = array (
      '#type' => 'submit',
      '#value' => t ( 'Lancer la simulation' ),
      '#weight' => 10000
  );

  $form ['simul_message_retour'] = array (
      '#prefix' => '
',
      '#suffix' => '
',
      '#markup' => isset($form_state ['input']['simul_message_retour']['#markup'])?$form_state ['input']['simul_message_retour']['#markup']:'',
      '#weight' => $form ['submit'] ['#weight'] + 1
  );
  if (!empty($form_state['response_module'])) {
    $form['simul_message_retour']['#markup'] = convert_data_to_markup($form_state['response_module']);
  }
  return $form;
}

/**
 * Validation Works
 */
function MY_MODULE_form_validate($form, &$form_state) {

  $form_numbers = array (
    //Some form fields
  );
  // operations of validation
}

/**
 *
 * @param unknown $form_element
 * @param unknown $form_state
 * @return Ambigous <multitype:, unknown>
 */
function MY_MODULE_format_simul_datenaissance($form_element, &$form_state) {
  //checking some of the form construction
}
/**
 * Function of submit
 *
 * @param unknown $form
 * @param unknown $form_state
 */
function MY_MODULE_form_submit($form, $form_state) {
  $form_state['response_module'] = project_call_WS($form, $form_state);
  $form_state['rebuild'] = TRUE;
}

/**
 * function processing the call to the WS
 * @param unknown $form
 * @param unknown $form_state
 */
 function project_call_WS($form, $form_state){
  // checking if there are no errors
  if (form_get_errors ())
    return '';

  //Operations on the form
  $url = implode ( '/', $url_array );
  $parameters = 'URLTOWEBSERVICE';
  // HERE IS CALLED THE WEBSERVICE(the function call_ws is working well)
  $call = call_ws ($parameters );

  $build = array (
      //ETC
  );
 //Operations on the $builds array
  return $build;
}

Thanks a lot

The form API and message system are not the same thing, even though there are helper functions in the FAPI to produce messages - you don't return a form with a message, you set a message when it's appropriate to do so. That might be when the form is being built, when it's being validated, after it's been submitted, and so on.

Generally speaking, if you're setting a validation error, use form_set_error() in a validate callback:

function MYMODULE_form_validate(&$form, &$form_state) {
  if (something_wrong_with($form_state['values']['foo'])) {
    form_set_error('foo', 'Run away, bad things happening');
  }
}

If you want a confirmation message on form submission, use drupal_set_message() in a submit callback:

function MYMODULE_form_submit($form, &$form_state) {
  if ($form_state['values']['foo'] == 'bar') {
    drupal_set_message(t('You chose: %foo', array('%foo' => $form_state['values']['foo'])));
  }
}

There's no point returning anything from a form submit callback - it will be ignored. If you want to rebuild the same form again after submission, use:

$form_state['rebuild'] = TRUE;

It may or may not be necessary depending on your final goal.


Front page redirects to user page I just installed D8, but when I try to reach the Front Page as an authenticated user, I got immediately redirected (302) to the user page. As a anonymous user, it works as expected.

I do not know exactly what additional data I should provide for debugging this issue, but will happly provided any information I can.

In the "Default front page" field at /admin/config/system/site-information, instead of leave it blank, insert /node which is normally what drupal places by default.


Webform Issue with Drop Down and Key not Equaling Value I have written a custom handler in Drupal 8 D8 that grabs submitted data from a webform and reformats it and sends it to a JSON webservice. That is all working perfectly. My issue is that the submitted data from 2 of the dropdowns is an integer (the key of the dropdown), rather than the value of the drop down, like it was when in D7 I called:

$components = $node->webform['components'];

which gave me the value of the data from the dropdowns. Now I am calling:

$values = $webform_submission->getData();

Which gives me the submission data. However, what I need to do is translate the number to the value. For example:

for a component (or element) drop down called 'numbers' the options are:
1|One
2|Two
3|Three

When I grab the submission data I get "1" but I want to send the word "One".

How do I load the dropdown element to translate the value '1' to the word "One" in Drupal 8?

Thanks.

When I grab the submission data I get "1"

This is standard in Drupal for select & radio fields, you always get the key.

So all we have to do is use the key to retrieve the value.

$key = $webform_submission->getData()['field_select'];

// retrieve webform fields.
$webform_fields = $webform_submission->getWebform()->getElementsDecoded();

// use key to retrieve value of field_select.
$value = $webform_fields['field_select']['#options'][$key];


How to get the body trimmed when loading nodes programmatically? I'm getting my nodes directly using db_query (I'm applying some specific conditions), so I can't use the render function allowing me to get the trimmed (or the summary) version of the body that I configured in the Manage display tab of my content type.

For perfomance issue I don't want to use the node_load function on each of my nodes.

Is there a way that I can use a Drupal internal function that would help me to trim the body value?

You can get the trimmed summary using text_summary() which will allow you to pass the text, input format and choose the text size (length) you want.


Insert a view into a block or a node using a shortcode I need the following:

I have a view that lists my portfolio projects the projects have a term reference field for its category. I want a shortcode for insert the view into some of my nodes and be able for apply arguments or filters for example:

Category 1 AND Category 2
Category 1 OR Category 2
Or simply listing the project node IDs: 333,332,334

I found the Insert view module with that module I can make a shortcode like this

[view:view_name==arg1/arg2/arg3]

but how I told you I need to be able for filter in the short code Category_1 AND Category_2 for example or list the given node IDs

How would you do this using Insert view module?

Your problem seems to be one of passing in context.

A better option is to install either the Display Suite Module, or Page Manger with Panels. It is great for passing context and creating custom views outputs on your node .With both of these options you have far more control, and if you invest in learning the ins and outs of at least one of them you will not be sorry.

I will walk you through using Display Suite:

Install CTools' Views content panes. Create a base view that lists whatever you need listed, then add a Content Pane (from CTools) to the view. Add a relationship to the term in question, and then any and all contextual filters that would be needed. Lastly, under PANE SETTINGS in views, click on Argument input, select From context for each of the contextual filters, and slect the required context for each of them.

Install Display Suite. In the display of your node type, select a layout (one column should be fine) to activate display suite to render that view mode. Create a new dynamic field. Drag it to wherever you want it displayed. Click on the gear next to it, and at the top would be a Edit content link. Click that, and select View panes, then the view you just created. It will then ask for you to select the context for each of your views contextual filters. Node being viewed is what you select.

Now when you view the node it pulls in that view with the required contextual filters and displays its output as a field.


dpm in submit handler not working? I have a very interesting problem.
I have 2 dev machines (both mac, running XAMPP).

In my project I have a submit handler for a custom entity form.

When I try to dpm() (or kpr, or dsm, ...) the contents of $form or $form_state, well, nothing really happens (on one machine!)

On the other machine, the dpm (for the exact same project, in the exact same submit handler, for the exact same variable) works perfectly.

I have copied php.ini settings files, checked the php memory limit, ...

Nothing seems different...

When I try to dpm($form['entities']); then it works on both instances.
This seems to give me the impression that it works when you narrow down the array...

But when I inspect the array ($form) it only contains approx. 40 items or so... (okay there are arrays in arrays and so on).

No errors on in the php log, apache log, ...

Any suggestions would be very welcome!

Many thanks in advance!

I had a similar problem. In a submit handler, tried to run dsm($form_state). This caused all submit handlers to not run. If I run $form_state['complete form'] = NULL; before the dsm(), it works. I presume it was too big with the complete form in there.


Programmatically validate a user I have created a webform which when submitted will create a new user for my Drupal 8 site.

The user must enter his username, email, and some additional data.

I am using below code to create & validate a user:

namespace Drupal\my_module\Plugin\WebformHandler;

use Symfony\Component\HttpFoundation\RedirectResponse;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;

use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
// use Drupal\taxonomy\Entity\Term;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Create New User Account when a webform submission is submitted.
 *
 * @WebformHandler(
 *   id = "Create New User Account",
 *   label = @Translation("Create New User Account"),
 *   category = @Translation("Entity Create"),
 *   description = @Translation("Create New User Account when a webform submission is submitted."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class CreateNewAccountHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

// Function to be fired while submitting the Webform.
public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

// Build Drupal DateTime & set correct format for your query.
  $current_time = \Drupal::time()->getCurrentTime();

// Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get 'Username' Value.
    $username = $values['username'];

    // Get 'Password' Value.
    $password = $values['password'];

    // Get 'Full Name' Value.
    $FullName = $values['full_name'];

    // Get 'Phone Number' Value.
    $PhoneNumber = $values['phone_number'];

    // Get 'Email' Value.
    $email = $values['email'];

// Create user object.
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $new_user = \Drupal\user\Entity\User::create();

    //Mandatory fields.
    $new_user->setPassword($password);
    $new_user->setEmail($email);
    $new_user->setUsername($username);    // Alphanumeric (abc, 123), space ( ), period (.), hyphen (-), apostrophe ('), underscore ( _ ), and the @ sign are only allowed.
    $new_user->set("langcode", $language);
    $new_user->set("preferred_langcode", $language);
    $new_user->set("preferred_admin_langcode", $language);
    $new_user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object.

    //Optional Fields
    $new_user->set("init", 'email');

    // Custom Fields
    $new_user->set("field_full_name", $FullName);
    $new_user->set("field_ph_nbr", $PhoneNumber);

    // Validate the user for possible errors.
    $violations = $new_user->validate();
    if (count($violations) > 0) {
      $property = $violations[0]->getPropertyPath();
      $msg      = $violations[0]->getMessage();

    // Show a custom message to user.
        \Drupal::messenger()->addError(t("$msg"));

      return FALSE;
    }

    // Activate the user Object (Status = Active).
    $new_user->activate();

    //Save user
    $new_user->save();

    // Get the new user ID.
    $new_user_id = $new_user->id();

    // Log in the user.
    user_login_finalize($new_user);

However, every time I try to create a new user using the webform, I got the below error:

This value is not a valid email address.

I have tried with:

someone@hotmail.com
someone@outlook.com
someone@gmail.com

What is wrong with my code ?

The error message doesn't specify which field caused the validation error. In this case, the error is caused by setting the init field with a value that isn't a valid email address.
Differently from Drupal 7, in Drupal 8 the init field for the User entity is created using the email datatype. (See User::baseFieldDefinitions().)
$fields['init'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Initial email'))
  ->setDescription(t('The email address used for initial account creation.'))
  ->setDefaultValue('');

Differently from the mail field, it doesn't get further constrains. (Compare the code used to create the init field with the following code.)
$fields['mail'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Email'))
  ->setDescription(t('The email of this user.'))
  ->setDefaultValue('')
  ->addConstraint('UserMailUnique')
  ->addConstraint('UserMailRequired')
  ->addConstraint('ProtectedUserField');

Still, as any entity field whose datatype is email, it has a constrain defined in the annotation of that datatype.
@DataType(
   id = "email",
   label = @Translation("Email"),
   constraints = {"Email" = {}}
)

(The classes defining that constraint are EmailConstraint and EmailValidator.)
Setting the init field for the User entity is optional, but it's generally used from administrators of a site when users claim they created an account for which they cannot retrieve the password they lost.
Depending on the purpose of the code you are using, you can either set the init field, or not. If you set it, it must set to a valid email value.


Extra handler breaks Datepicker field Problem

I have a form which a user can create data with and some of the fields are date fields which use jQuery datepicker.

The form is long and in order to help the user out, I have a series of help messages which appear when the relevant form input is focused.

When a form element is given focus, the form's ID is grabbed and attached as a class to the help div, which reveals the correct help message.

Example: jsfiddle - caveat in a moment

This works in the jsfiddle, however in Drupal it breaks. On click the calender opens but rather than selecting a link it hits the local hyperlink "#" below it and changes the url to http://mywebsite.com/form/#

The problem appears to be related to how the Drupal date jQuery module deals with Datepicker. I've narrowed it down to something to do with $(this).attr('id'), it doesn't like the that selector but I'm unsure as to why.

Full Script

  Drupal.behaviors.jobhelpAddClass = {
    attach: function (context, settings) {

      var jobHelp = $('#jobhelp').children();

      $('input, select').focus(function() {
        $(jobHelp).attr('id', $(this).attr('id'));
      });
    }
  };

I've tried with document ready instead of Drupal behaviours and it still breaks. I've also tried getting focus to call a function (with the same code), however neither works.

Looks like the problem is with the CSS rather than the id part. The typical id would be something like this: edit-field-date-und-0-value-datepicker-popup-0 and this id is dynamically generated and not grandee that it would stay same (i.e. you may get edit-field-date-und-0-value-datepicker-popup-1 if you have the same field twice in the same form).

You can use name instead of id. Here is the working fork of your jsfiddle with name: http://jsfiddle.net/vijaycs85/C4sh9/


What are folders within sites/default/files for? There is a quite similar question in What are all the directories for in the new Drupal 8 structure? about the Drupal directory structure, but it is not explained the content of the sites/default/files directory.

Within such directory there are all these folders:

2016-01/
2016-02/
...
config_nEjJjnck1_CMDKmCKDLS9cd-CKD89cdsCD78cdsCNJD89/
css/
inline-images/
js/
languages/
php/
styles/
translations/

First two folders contains user-uploaded content. What are other folders for and how/when their content is generated? Which of these folders should be included inside a Git repository?

They're created by different parts of the system, when they're required, for pretty much anything at all that a module needs to store file-wise.

It would be pointless to try to list them all, as core/contrib/custom modules can place files/folders there arbitrarily; Drupal doesn't place any restrictions on what can/can't be stored there, it's up to each bit of code as to how and when it uses that folder to read/write.


How do I redirect a taxonomy menu item to another path? I have a taxonomy menu, and I want to redirect the page request from taxonomy/term/% to a custom path using a page callback function.  How can I use a function to cause the redirect?

If I understand you want to implement hook_menu_alter() and override the page callback for that path:

function MYMODULE_menu_alter(&$items) {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'MYMODULE_taxonomy_page_callback';
}

function MYMODULE_taxonomy_page_callback($term) {
  // Either redirect the page
  drupal_goto('somewhere');

  // Or build up some output to replace the original taxonomy term page.
  // This way you won't actually have to do a redirect at all
}

If I can offer a bit of advice, keep this callback function in your module file so it's always included. Otherwise you'll need to change the file property of the menu item too and that can get quite messy as Drupal is expecting the file to exist in the path that the defining module is in (in this case the taxonomy module).


Media queries only applied for authenticated users i'm working on a responsive theme using compass / susy, and i had issues on application of media queries.For example, images weren't responsive on mobile, or weren't on full size for desktop.
i did test on different browser and the only one that work were one for connected user.so i did connect me under others browser and media queries were applied.
so what can i do to fix this uge problem ?

thanks

As Molot commented it is just a cache problem. You need to clear your browser cache to get the updated css. Another trick that works for me is to add a query string in the URL (e.g http://example.com/node/test?awy). You may need to turn off the css aggregation under Performance page to make sure that you will get the updated css and not the cached copy.

You can use Drush to clear your cache by using drush cc all.


Drush site upgrade: Contributed extensions were not upgaraded I am using Drush site upgrade module for D6 to D7 Upgrade.

In step 15, drush asks me to update only one module i.e. path_access, and for all the modules it says "following contributed extensions were not upgaraded". Then in final step its says "there are no more modules to be upgraded".
And my all contributed modules remained unupgraded.
Should I need to upgrade them manually.

I think you should Migrate d2d module for content migration and also should upgrade contributed modules manually as might be some modules aren't supported in drupal 7. So, this should be a manual task. But using Migrate d2d module, you should be able to migrate content :).

I guess this is helpful to you.


Include image in RSS feed Views display I'm creating an RSS feed of a basic Blog using Views. This is being picked up by Facebook's Graffitti module. Everything works fine here, except that the image isn't being added to the RSS feed... I've incuded a screenshot of my views settings... I'm using a Style of RSS Feed and Row Style: Node (this is the only type allowed).

How can I get a link to the image into feed?!

screenshot

If the image is a CCK field, make sure the correct formatter has been selected for the image field and it has not been excluded from the RSS display at admin/content/node-type/YOUR-TYPE/display/rss.

If it's an attached image, check that it is displayed as part of teaser (or full body) and that Feed content is set to teaser (or Full text) at admin/content/rss-publishing.


bookmark organize for anonymous user permission I have use drupal 7. I download and install the flag , flag bookmark, bookmark module.I have also add settings for bookmark. Bookmark functionality is work for authenticated and admin user. i wanna functionality for anonymous user. So how can I use for anonymous user ?

I have check the permission but they can't provide the permission for anonymous user.

so can you explain me how can I do this task ?

To my knowledge, the features of the flag module are designed to be used by authenticated user only, so not by anonymous users.

The closest you can come to address your question, is as is described in How to display a flag to anonymous users?, i.e.:

  When an anonymous user clicks on flag, then such user should be redirected to the login page. After login the user should be able to set flag.

And then do as described in the answer to that same question, i.e.:

  You can do this in your 'node.tpl.php' ...: if user is logged in then display flag as normal; if not logged in then redirect user to logging page with destination parameter.


Custom tokens in custom module The story :
I create lets say a simple module to store input data and sent a mail when you click save.
Now i done the part of store data, send mail and retrieve data, but i would like to add tokens to the mail part.

So for now i have something like this.

 function mymodule_form (){
         $form['name'] = array(
        '#title' => t('Your name'),
        '#type' => 'textfield',
        '#size' => 60,
        '#maxlength' => 100,
        '#description' => t('Input your first and last name.'),

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

    return $form;

}

Now you have mymodule_submit that saves the data and sends mail.

function mymodule_submit(){

 here goes the part for saving data into table(not going to write it)....

/*mail send*/
    $text=array();
    $subject=array();
    $mail = db_query("SELECT * FROM {mail_data} WHERE mail_id=2");
    foreach ($mail as $data){
        $text = $data -> text;
        $subject = $data -> subject;
    }

    $params = array(
    'subject' => $subject,
    'body' => $text,
            );
     $to =$emailto; //db_query that selects from table
     $from =$emailfrom; //db_query that selects from table
    drupal_mail('person', 'my_module', $to, language_default(), $params, $from, $send = TRUE);

    /*end mail send */

}

function mymodule_mail($key,&$message,$params)
{

  switch ($key) {
    case "my_module":
        $message['subject'] = $params['subject'];
        $message['body'][] = $params['body'];
      break;

  }
 }

Now I made a form for inserting subject and body of mail hence $mail = db_query("SELECT * FROM {mail_data} WHERE mail_id=2");

My question is how can i allow user to use tokens or something else to add tokens like in drupal account mail settings(like: account activation, account blocked etc...), where you can add tokens to text so that you get :

[user:name],

A site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:

[user:one-time-login-url]

So to clarify ... I have a form that user uses to input mail data but for now he can only input text , i want to make it possible for him to use tokens(or something else like drupal_set_message(t('Saved input @var!', array('@var'=>$temp)));) when he inputs data...

Its a form like mymodule_form.

You would have to add them to a global token piece like [site] for them to be able to be used anywhere tokens are used.

But to use in a custom module you can use the following hooks:

Generate token info:

/**
 * Implements hook_token_info().
 */
function module_name_token_info() {
  $info = array();
  // Define a new token type.
  $info['types']['my_custom_tokens'] = array(
    'name' => t('My custom tokens'),
    'description' => t('A token type for my custom tokens.'),
  );
  // Define any new tokens.
  $info['tokens']['my_custom_tokens']['my_token'] = array(
    'name' => t('My token'),
    'description' => t('A token I use in my module.'),
  );
  return $info;
}

Give values to token:

/**
 * Implements hook_tokens().
 */
function module_name_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'my_custom_tokens') {
    // Loop through the available tokens.
    foreach ($tokens as $name => $original) {
      // Find our custom tokens by name.
      switch ($name) {
        case 'my_token':
          // Work out the value of our token.
          $value = 'Value of token';
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
      }
    }
  }

  return $replacements;
}

That should get you started with custom tokens. I've used this a few different times with different situations and it works very well.


Unable to redirect after user_save I am unable to redirect back to the page after executing the user_save. Following is my code snippet:

//if the response code is failed rollback the user changes and redirect
if ($results['code']!=200) {
  user_save(NULL,$account);
  drupal_goto("/admin/people");
}

Please check the below format:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'form_id_goes_here') {
    // Code here
    $form['#submit'][] = '_mymodule_test_registration_submit';
  }
}

function _mymodule_test_registration_submit($form, &$form_state) {
  // Code here
  $form_state['redirect'] = 'path1/path2/mypage';
}


Change on/off values for existing boolean checkbox Trying to find most "soft" way to alter data for already existing checkbox field. Aiming to change the labels value for on/off but updating them from UI or programatically is not working out, field_config contains proper allowed values array. Im not sure where else too look, on node view Im still seeing 0/1 values event though I changed the on/off values to string representations. I know I can do it on node view alter but I want more general solution, also deleting the field base and recreating is not an option here. Any hints?

Solution was to reexport into features field_base and field_instance proper labels, then to make sure field_config and field_instance_config blobs are properly updated. I used update hooks to resave the fields with proper info, I loaded them with field_info_field, set the required properties and the used field_update_field. Also field config from list_key must be changed to list_default.


Webform translation while keeping single node I want to translate a Webform. I know it's very easy to achieve if there are separate Webform nodes for each language but I don't want to do that, I want to keep a single node.

I have already tried the Webform Localization module:

As per the readme of this module, it says to keep a single node enable
"localization by string translation" fieldset in the form settings

Which I have done.

I have also refreshed the i18n_string, as suggested in module readme.

Issue here is, even with above settings when I click on translate tab of the Webform node, it creates new node.

So are there any other settings I'm missing or this module is not working as its currently in under development.

The method in the documentation is working:

Go to the Webform Form settings at node/1/webform/configure
Check "localization by string translation" and "Expose webform
component strings suitable for translation."
If dealing with an existing webform, then go to Go to Configuration -> Translate interface -> Strings
Enable "Webform localization" checkbox (this is important)
And Refresh Strings
Then you will be able to see the string in Configuration -> Translate interface -> Translate

At least this works for me.


Make variable available in template file I am creating a custom template file for a views table and I need to put some links in the footer of the table, these links belong to 3 nodes. How can I make this data available in my template file which is - views-view-table--my-view-name.html.twig

Is there a pre-process of some sort that I can use?

You can override template_preprocess_views_view_table() in your own THEMENAME.theme file

function THEMENAME_preprocess_views_view_table(&$variables){
   $variables['node1'] = "value from node 1";
}

in your twig file you should have the variable available

{{node1}}


How to add fields to 'content' format in Views I created a view from  node. In the FORMAT settings, I choose content (because I need to display the comment form). How do I add fields such as post date or Share this link (ShareThis module) to the view?

Here are the steps:

First you need to configure "share this" module:

Go to Configuration >> Web services >> Sharethis (admin/config/services/sharethis)

select the Node Types where you want to use this.

Then go to content type manage display settings and in custom display settings check the modes which you have used in view.

That's it.


fboauth get user info I implemented fboauth module. It works fine and I can to link my site's account with facebook account.

I need if user logged in and his account is linked with facebook, show his picture at some block, else don't show picture or show some other picture.

Can you help me?

If you use the function fboauth_fbid_load() you get facebook id or FALSE.
With the facebook id you can obtain profile picture.


webform blank page D7 The Webform module is installed. I go to /admin/content/webform to build new form, but the page is completely blank. The content is empty. What am I missing? Is there an additional library I need?

I do have Views and Chaos Tools installed. And my administrator role has permission to modify webforms.

There is a Webform issue which might be similar to this question here. Though that issue is after "upgrading", one could argue that after "upgrade" or after "install" of the module, the result is in both cases that you are using the newest version of the module, right?

So therefore, here are a few things in that issue that might help to get you going:

Clear the cache and try again.
if you did something like an update of that module (I think not, but you never know), then run update.php and try again.
Try to disable and then enable the module, and try again.

Curious to hear if any of this helps ...


A way to make one Drupal site act like several sites I would like to create several sites each with same number of features (content types) but the ability to select different theme.
If I go with multisite feature of Drupal I will have difficulty in setting up and managing all the sites.

I can achieve different sites with Organic groups. But the spaces module is pretty much not working and needs serious development for 7.x version. I tried with all the patches but still it gives me a lot of trouble.

My requirements are more or less same as OpenScholar distribution but I would rather like to use Panopoly (panels) than boxes and context.
Also Openscholar has way too many features that I dont care of and exerts some serious load on the server.

Are there any alternatives to spaces module? Any help would be appreciated. a Case study perhaps.

Have you looked at the Domain Access project?


Dynamic hook menu to redirect user I'm trying to essentially create an alias to an entity edit form, but really all I need to do is redirect, but get a Page Not Found error.

function kidb_profile_menu() {

    $items['profile/%uid/edit'] = array(
        'page callback' => 'kidb_profile_redirect_user',
        'page arguments' => array(1),
        'access callback' => array('edit own main_profile profile'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function kidb_profile_redirect_user($uid) {
    drupal_goto('profile-main_profile/'.$uid.'/edit');
}

Since you are using the %uid wildcard in the menu definition, your kidb_profile_redirect_user() is not getting a user ID, but what uid_load() would be returning. That function is not defined from any module and that is the reason why you get the "page not found" error.

The list of wildcards defined from Drupal 6 is reported in Wildcard usage and core's wildcards. A description of what auto-loader wildcards are is given in hook_menu():

  Wildcards in Paths

  Simple Wildcards

  Wildcards within paths also work with integer substitution. For example, your module could register path 'my-module/%/edit':

  $items['my-module/%/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

  When path 'my-module/foo/edit' is requested, integer 1 will be replaced with 'foo' and passed to the callback function. Note that wildcards may not be used as the first component.

  Auto-Loader Wildcards

  Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule_abc' part defines the prefix for a load function, which here would be named mymodule_abc_load(). When a matching path is requested, your load function will receive as its first argument the path component in the position of the wildcard; load functions may also be passed additional arguments (see "load arguments" in the return value section below). For example, your module could register path 'my-module/%mymodule_abc/edit':

  $items['my-module/%mymodule_abc/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

  When path 'my-module/123/edit' is requested, your load function mymodule_abc_load() will be invoked with the argument '123', and should load and return an "abc" object with internal id 123:

  function mymodule_abc_load($abc_id) {
    return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
  }

You probably meant to use %user, which would return to your page callback the object returned from user_load(). Using that wildcard avoids you check in your code that the user ID is valid (e.g. there is a user account with that ID), but also means that you should change your code to match the following.

function kidb_profile_redirect_user($account) {
  drupal_goto('profile-main_profile/' . $account->uid . '/edit');
}


how to send multiple attachments with drupal_mail_system I can programmatically send emails with an attachment with problem.  But after searching I can not seem to find the solution of how to attach multiple files. Does any one have the code to this.

Here's the working code I have for sending email.

$mail = variable_get('site_mail', '');  // sets the site wide email address

      $my_module = 'Email Application';
      $my_mail_token = microtime();
      $from = $sender;
      $message = array(
        'id' => $my_module,
        'to' => $app_email,
        'subject' => $subject,
        'body' => $body,
        'headers' => array(
          'From' => $from,
          'Sender' => $from,
          'Return-Path' => $from,
  ),
  );

$message['attachments'][] = drupal_realpath($attachment_path);

$system = drupal_mail_system($my_module, $my_mail_token);

You're using $messages['attachments'] as an array, so presumably just add another item to the array:

$message['attachments'][] = drupal_realpath($attachment_path);
$message['attachments'][] = drupal_realpath($another_path);
$message['attachments'][] = drupal_realpath($yet_another_path);


I can't add to cart without HTTPS enabled I have a quite weird situation here, I assume this problem must be a server side issue, but so far I couldn't figure it out how to fix this.

I have a Nginx server with Varnish (I even disabled it totally still got the error) running a Drupal Commerce website on it, the quite funny issue here is the "Add to Cart" button doesn't work on a session without HTTPS, if I add HTTPS in front of my URL, I can add the product to my cart!

I'd really appreciate any help!

The problem was that commerce_cart.module requires a valid session or logged-in user.  The security settings of the OP's site prevented sessions being sent out to HTTP requests.
While the OP solved this problem via PHP.ini, there are other valid solutions:

Adding session.cookie_secure = 0 in settings.php
Requiring all users to use HTTPS.
Preventing the cart from displaying to anonymous users.


What is the proper way to set up an AWS Auto-Scale group? What is the proper way to setup an EC2 Web Server with the aim of serving a site which experiences high demand once a month via 1 small EC2 for 90% of the time and then enter a load balanced group for the other 10%.  I understand the AWS mechanics, AMI, auto scaling, metrics, and load balancer, but I don't know the best practices of setting up a CENTOS server to serve multiple servers.

I was thinking http://tecadmin.net/mount-s3-bucket-centosrhel-ubuntu-using-s3fs/# with S3 buckets (I ran into a few problems), but would a simple mounted volume be better?

I would really appreciate advice from anyone who has used AWS in this way with Drupal.  Another article I read is Using a load balancer or reverse proxy.

Obviously, performance is a big consideration. I know S3 is fast, but I imagine it's slower than using a mounted volume.

Drupal considerations are similar to WP, Magento and Stateless applications.

Share your code across your auto scaling group via AWS EFS, Lsyncd, S3 or NFS.
Use CDN + S3 for static content
Separate Database (AWS RDS)
Make sure to use Varnish and NGINX.
Use Github/BitBucket and define a development workflow system.
Cache and manage session via Redis/Memcached.

More details: https://www.clickittech.com/cloud-computing/scaling-in-the-cloud/

The above link is an article about the Art of scaling which considers Drupal, WP and Saas Applications.


Views contextual filters summary display nodes id instead of title I have a content type customers who has a required entity reference field to a content type groups. I have create a view to show all customers nodes and I have added a contextual filter over the entity reference field to display a summary of groups with a count of customers per group. The view uses fields, and I have added nid, title and reference field from the customers content type.
It works good and if no group is in the argument, It shows the summary, but instead of display the titles of the group, It display the nid of the group.
Following this answer I have put the title when a group is selected, but the summary shows nids.
What should I do to show this nodes titles?

Edited:if I do exactly the same with D7, it shows the titles as expected.

I have found how to do it. Firstly, I added the relation between customers and groups in the "relation" section. After this, instead of adding the relation field as contextual filter, I added the title field as contextual filter, but I checked the relation I have created. Then, when the argument is not present, It shows a list of groups (with their names) and the count of record.


Blank Page Template for ajax requests I'm still pretty new to Drupal. I needed help creating a blank page template for a certain content type. When I say blank, I mean the only thing thats displayed on the page is the render($page['content']) information. None of the markup that is added with the html.tpl.php template.

To give you a wider perspective of what I'm trying to accomplish - I'm trying to use the assets that are housed here in an .ajax request to display elsewhere.

Thanks for your time.

Personally I deal with situations like this in a custom module by registering a path with a callback function that prints the needed content:

function mymodule_menu() {
  $items['somepage/%'] = array(
    'title' => 'Somepage',
    'page callback' => 'mymodule_ajax_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_ajax_callback($nid) {
  if ($node = node_load($nid)) {
    $view = node_view($node, 'full');
    print drupal_render($view);
  }
}

This would get you the view of node 12 without any external markup on 'somepage/12' for example. Note that when you use return instead of print you get the page with additional markup added (just for future reference).

If you want to go with the template approach you could create 2 templates: 'html--blank.tpl.php' and 'page--blank.tpl.php'. The first one should contain only <?php print $page; ?> and the second <?php print render($page['content']); ?>. In your template.php file add:

function mytheme_preprocess_html(&$variables) {
  if (isset($variables['page']['content']['system_main']['nodes'])) {
    $nodes = $variables['page']['content']['system_main']['nodes'];
    $key = key($nodes);
    if (count($nodes) == 2 && $nodes[$key]['#node']->type == 'my_content_type') {
      $variables['theme_hook_suggestions'] = array('html__blank');
    }
  }
}

function mytheme_preprocess_page(&$variables) {
  if (isset($variables['node']) && $variables['node']->type == 'my_content_type') {
    $variables['theme_hook_suggestions'] = array('page__blank');
  }
}

These solutions will give you a slightly different result, but either should get the job done (just remember to modify them to fit your needs and clear the caches).


How to display one of the fields once in drupal views? I have created a gallery view using nid as contextual filter, all images have the same album title. I need to output the album title field once. How can this be done?

I'm using views 3.

Select settings in Format field,and select the title under Group field selectlist.


Views exposed filter redirects to wrong url After submitting the filter settings, on a page (panel in ctools Page manager module) with view content pane, the filter path (in URL) instead of being applied to the current page (with view), it is added to the root domain (home page).

Please give a tip what might be wrong with settings?

View Settings - PANE SETTINGS (middle column) - Use Panel path:Yes


How to add a permission : reorder Taxonomy terms I need some roles to be able to edit and add terms of specific vocabularies, but not to reorder them. How can I add the permission reorder foo vocabulary terms, reorder bar vocabulary terms... with a module or programmatically ?
AFAIK edit terms permissions immediately give you the permissions to reorder terms also.
I already tried these modules below but none implements such permission.
Vocabulary Permissions Per Role

Allows adding to/editing terms of/removing terms from vocabularies per
role... adding terms to a vocabulary but not to another, reordering/editing terms of a vocabulary but not another's, etc.

Says so, but reordering /editing come together.
Taxonomy access fix

adds 1 permission per vocabulary: "add terms in X"
changes the way vocabulary specific permissions are handled
changes the Taxonomy admin pages' access checks
alters the vocabularies overview table to show only what you have access to edit or delete

The module does what native Taxonomy lacks: more specific Taxonomy
permissions (and checking them correctly).

Thank you.

You need to implement hook_form_alter  and remove the Sort alphabetically button based on the role.

Edit: Something like this (tested)

function mymod_form_alter(&$form, &$form_state, $form_id) {
  if (in_array('userrole', $user->roles) && ($form_id == 'taxonomy_overview_terms') {
    unset($form['actions']['reset_alphabetical']);
    drupal_add_css(drupal_get_path('module','mymod').'/css/mymod.css');
  }
}

and in css/mymod.css, do

.handle,.tabledrag-toggle-weight {display:none;}

This hides the Reset to alphabetical button, drag handles, and Show row weights link.


Button that executes php function, or custom VBO action I have a function that pushes a node to a sugarCRM database. There have been some problems with the sugarCRM database recently and some of the nodes that were supposed to be pushed were not. I need to be able to build a button that can execute the function manually and push the selected node to the database. Is there a way that I can accomplish this via VBO?

You can create a menu item that does what you want along the lines of

function YOURMODULE_menu() {

  $items=array();

  $items['sugarme/%'] = array(
    'title' => 'Send this node to sugarCRM',
    'page callback' => 'YOURMODULE_sugarme',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  // other menu items here

}

function YOURMODULE_sugarme($nid) {

   if (YOURFUNCTIONTOSENDTHISNIDTOSUGARCRM($nid)) {
     return 'Sent to sugar';
   } else {
     return 'Send to sugar failed';
   }

 }

which in the very simple form above (no security, no argument sanity checks, etc) creates a path on your system www.yourhost.com/sugarme/#### that will call your function with the nid passed to it.


Custom query in Views? At some point I found the need to modify an SQL query generated by Views, in the end I overrode views_pre_execute and changed the query for that specific view.

This feels like an ugly hack to me and I wonder if there is a more elegant and maintainable way to do that. Ideal would be a way that would allow me to directly modify the query from the Views UI.

You can also use hook_views_query_alter() to alter the query before it's run. I think this is similar to hook_views_pre_execute, but makes it easier to modify the query. You basically get access to each part of the query through a keyed array. I haven't found much official documentation, but there's a pretty good example of it at https://www.appnovation.com/blog/using-hook-views-query-alter. This is also the approach I had to use to fix a date bug in the Calendar module.


How to setup different confirmation email per webform instance Background:
I have a ContactUs webform made by Drupal 8 webforms contrib module and used that ContactUs Form on 3 different pages.

Is it possible to setup 3 different confirmation emails per instance?

Many tanks

You can pass a custom confirmation message from a Webform node to the Webform email handler using a token like [webform_submission:node:field_confirmation_message]


How to display the alt below images in Panels? I have a drupal site which sells variety of products.
I set a content type for my product and use panel for the layout.
Basically, the text is on left, and images on right
Is there anyway So I can Display the alt text below images because they are very valuable keywords for SEO and customer.
I can't find the any tokens of node field to import into panel.

Can anyone help me with this? Thank you very much.

If you add your images by using content and content type, this might help.

Content type -> one of the list -> manage field

click on image hyperlink follow by edit tab

Check Enable Alt field and it wil appear in edit content.

Hope this help.


How to theme separately the node content and the comments I have seen here several related questions, none of which clearly provide an answer. I am implementing a theme where I want the node content (with its title, the tabs, etc.) themed completely separately (i.e. in a different div) from the comments. The initial problem is that part of what I consider the node content (the title, the tabs) is rendered in page.tpl.php and part (the node body itself) is rendered in node.tpl.php. The problem is that the comments are an integral part of the variable $content in node.tpl.php.

I found part of the solution:

I found the template comment-wrapper.tpl.php. By reimplementing it in my theme, I can cancel the output of the comments (by blanking out the template).

Now, I would like to use mytheme_preprocess_page() to pull up the comments into a variable $comments so that I can add the comments where I want in page.tpl.php.

The remaining problem is how can I get all the variables originally available within comment-wrapper.tpl.php from mytheme_preprocess_page()?

Or do you know another (better) way to achieve the same thing?

Another way to answer the question: who calls comment-wrapper.tpl.php ?

Maybe an answer to that question would help:
$content: reworded about manipulating this variable

A- The node_menu (hook_menu implementation) has node_page_view() as a page callback for a node page.
B- node_page_view() calls node_show() which:
1- is not a themable function.
2- mixes (concatenates) the output of node_view() (the node content itself) and of comment_render().
C- comment_render() calls theme('comment_wrapper', ...)

This is where the serpent bit its tail:
As mentioned in the question, I could reimplement comment-wrapper.tpl.php to nix the output mixed with the node,
but then calling comment_render() separately to get the comments where I want returns nothing for the same reason!

The conclusion is that the solution cannot be implemented by a theme alone. One would need to implement this in a module and override the node_page_view() callback and re-implement node_show(), taking care of the fact that node_show() is also called when viewing a node revision ('node/$nid/revisions/$vid/view').


How do I render a form as a table? The default form layout has each form element wrapped in individual div tags, with a label, and input inside. I would like to lay things out neatly, and create a column for the field labels, and another column for the input areas.

I can see this being accomplished in one of two ways:
- I could create a table, using table elements or divs, and separate the labels from the inputs. Would I use Twig for this?
- Alternatively, maybe there's a creative way to use CSS with the default structure to make everything look good. If there is, I can't figure it out.

How should I implement one of these, or another way to accomplish the same thing?

I had forgotten about the table-cell and table-row diplay properties. Despite the fact that CSS is off topic, the way to do it given Drupal's  form class structure is:

.form-no-label {
    display: table-cell;
}
label {
    display: table-cell;
}
.container-inline {
    display: table-cell;
}
.label {
    display: table-cell;
}
.form-item {
    display: table-row;
}


Is accessing the current node from multiple block plugins on a single page costly from a performance perspective? I use a combination of Block plugins and panels to populate the layouts of the display modes of various content types.

Here's an example:

class MyBlockPlugin extends BlockBase
{
    /**
     * {@inheritdoc}
     */

    public function build()
    {
        $node = \Drupal::routeMatch()->getParameter('node');
        $profile_pic = ImageStyle::load('350x300')->buildUrl($node->field_image->entity->getFileUri());
        return [
            '#theme' => 'mytwigtheme',
            '#name' => $node->title->value,
            '#headshot' => $profile_pic
        ];
    }
}

It certainly works but I'm wondering if this is a bad path to travel because I'll have multiple block plugins loading and accessing the same node. I suppose I could access the node with a preprocess block hook but I'm assuming that will load for every block as well.

If the performance cost is trivial then I'm not too worried about redundancy. Is my method okay? If not, what would be a better way for a block plugin to access the data of the current node it appears on?

Update:
Just another thought. Is me using a twig template making this a non issue as long as it's been loaded before?

No performance issue concerning the node entity, which is loaded only once per request and then stored in memory.

For caching between requests there are also no performance issues, because the rendered twig template(s) of a block are cached by default. But you have to make sure you provide the correct cache data, which is possible via a plugin context in the annotations (preferred) or by adding the cache metadata to the render array. See Block cache depending on current node and its last modification time


PDOException Error While saving the view I get this Error when i save a view of format JCarousel.

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry 'slidersidebar' for key 2: INSERT INTO {views_view}
  (name, description, tag, base_table, human_name, core) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5); Array (
  [:db_insert_placeholder_0] => slidersidebar [:db_insert_placeholder_1]
  => [:db_insert_placeholder_2] => default [:db_insert_placeholder_3] => node [:db_insert_placeholder_4] => Slider Sidebar
  [:db_insert_placeholder_5] => 7 ) in views_db_object->save_row() (line
  2092 of
  /home/kumarang/public_html/sites/all/modules/views/includes/view.inc).

Run update.php for your site; clear cache as well.


Installation keeps complaining that Unicode library (mbstring) should be disabled, even though it seems it already is I'm trying to install Drupal 8.1.3.
(Apache 2.4.7, PHP 5.5.37, Windows 7)

In the "Verify Requirements" step Drupal keeps complaining

  Unicode library -- Error -- Multibyte string input conversion in PHP
  is active and must be disabled. Check the php.ini mbstring.http_input
  setting. Please refer to the PHP mbstring documentation for more
  information.

However, I already have the following in my php.ini

mbstring.http_input = pass

and the diagnostic output produced by a call to phpinfo(); contains

zend.multibyte  | Off | Off

So I am not sure whether

I was unsuccessful in switching off the multibyte string input conversion,
I am looking at the wrong configuration files / settings, or
Something is wrong with Drupal's detection of these setting (see for instance this discussion on a failing detection).

http://php.net/manual/en/mbstring.configuration.php#ini.mbstring.http-input

Drupal's code is checking it in core/lib/Drupal/Component/Utility/Unicode.php, but it won't even check if unless PHP version is < 5.6.0.  If you are using PHP 5.5.x here's the check:

  if (ini_get('mbstring.http_output') != 'pass') {
    static::$status = static::STATUS_ERROR;
    return 'mbstring.http_output';
  }

So I would double check the phpinfo via the Drupal interface at /admin/reports/status/php to make sure you are changing the config file that's used by PHP for Drupal.


Use text field value on another text field on same node on save I have two fields on a Content Type called Property that requires the same information and I am trying to have it so that it only needs to be inputted one time be the user.

I am using the module Address Field and Locations and need to fill out the zip codes with the same zip code. I need to get it so I only have to input the zip code one time and it fills both. I have tried a hook form alter (my example below) but the second field does not get the text unless I save the node again. I understand why but I am not sure how to go about fixing this.

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

switch($form_id) {

  case 'property_node_form':

$form['locations'][0]['#default_value']['postal_code'] = $form['field_address']['und'][0]['#address']['postal_code'];

  break;

}
}

Suggestions welcome. Thanks!

What you are doing is happening in the browser, so drupal, or anything else on the server, obviously doesn't know what's going on until you hit submit.

So you have to use jQuery that is running there in the client, and one way would be along the lines of:

$('#IDOFYOURFIRSTZIPCODE').live('change', function() {
  $('#IDOFYOURSECONDZIPCODE').val($('#IDOFYOURFIRSTZIPCODE').val());
});

The #IDs will look something like #edit-field-FIELDNAME-0-value but basically what it is doing is changing the second value to the first when the first changes.

Put that in a module's or theme's js and you should be set.  (I suppose you could [should?] add it with a drupal_add_js() right from your form_alter().)

(For those jQuery experts out there, I suppose I should have used on() or delegate() instead of live() but this works on both D6 and D7 with stock jQuery)


Customizing webform results submission page I'm new to drupal. I'm using the Drupal 7 version. I have created one webform with Name, gender, program, branch, district, college..etc fields. And now I want to customize the webform result submissions page. I want to display the submission list based on the district selected. Can anyone help me with this? I will be very thankful.

Look at EntityForms to have more control over submissions and selecting what submissions to view.

Features
Ability to attach any Drupal Field to the Forms
Ability to use most field based and entity aware modules.
You can download submitted data to XML and / or CSV data files using View Data Export.
Rules based form submission notifications. Allows for complex notifications logic.
Rules based form access control. Allows for complex access logic.
Use Views to create to create an administrative listing of each Entityform type Submissions for fine grain control.


Issue in converting a HTML Link to Drupal Link using l() function I have created a HTML anchor link. Now i need to convert this link to Drupal's link using l() function. But i am not getting what i want. I am new to this Drupal environment.

HTML Link :

'.START_QTIQUIZ.'

What i have tried is,

l('Start QTI Quiz', '#', array('','onclick' => "loadQtiPlayer('.$targetPath.','.$targetWindowHeight.','.$targetWindowWidth.')"));

This is not working. I am using Drupal 6.14.

Can anyone point out where is the issue?

$current_path = check_url(drupal_get_path_alias($_GET['q']));
$onclick = 'loadQtiPlayer(' . $targetPath . ',' . $targetWindowHeight . ',' . $targetWindowWidth . ')';
print l('Start QTI Quiz', $current_path, array('fragment' => ' ', 'attributes' => array('onclick' => $onclick)));


Form API adds word "edit" in ID of every Form element FORM API adds word "edit" before the id of any form element. When I have to use the element in JS  I have to add "edit" before element id.

Example if I have element $form['curdate'] then in drupal_add_js('#edit-curdate');

Why so

Drupal adds edit to denote that the element is an input element. It helps to identify form elements through CSS, and reduces the possibility of ID clashes with other elements on the page.

In case you're interested, this is done in the form_builder() function...and there's no easy way to override it system-wide.

You can easily override it for individual form elements though if it's bothering you:

$form['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Some title',
  // ...
  '#id' => drupal_html_id('my-new-id')
);


Media library widget: Table instead of grid? Background
I have a multiple-value entity reference field with target type = media.
It is used for "document" media, so mostly pdf files.
I am using the "Media library" widget shipped with core.
With this widget, items appear in a grid with thumbnail, and can be reordered with drag + drop.
Problems
Most of the pdf files don't have a useful thumbnail, so they all look the same.
Due to the grid display, the title of each document is not fully visible.
The grid drag + drop reorder is less intuitive than a tabledrag, especially if the thumbnails all look the same, and sometimes even the visible part of the title is the same.
Once a media entity is added to the list, there is no link to edit this media entity from the node / host entity form.
Questions
Is there a table version of the media library widget?
Is there a way to show an edit link with each item? Either to edit the media in a form on a new page, or in a popup.
What I tried
Widget settings?
-> The widget does not have any settings.
Configure the display of documents in "Core | Media library" view mode?
-> Items still displayed in a grid.
-> The only field that looks well in a grid mode is the thumbnail. Text fields look weird.
References
Poor soul who asked the same in drupal.org, with no success: https://www.drupal.org/forum/support/module-development-and-code-questions/2020-06-29/how-set-media-library-widget-to

In response to your second question, there is a core issue open regarding editing media items within the field widget:  https://www.drupal.org/project/drupal/issues/2985168
There is also a contrib module Media Library Edit.
One problem is that you will edit the media entity itself, affecting all usages of the media item.


archive_page() from archive module in drupal 6 shows all nodes not date specific I installed Archive module and used following code in a custom template:

print archive_page('all', 2012, 10, 12);

but it shows every single node I posted, How can I make it load nodes according to date I specified in the code?

I just tested archive page in Drupal 6.26 and using Archive 6.x - 1.4 . It is working as expected.  Maybe you are  date and month in the archive_page. Please find the detailed explanation below.

The parameters of archive_page() are the following ones:

$year
Number of year.
$month
Number of month.
$day
Number of day.

So print archive_page('all', 2012, 10, 12); will return the nodes created on October 12, 2012. I just followed the below process to verify the functionality.

I installed archive module
I enabled the module
I enabled content types in "admin/settings/archive"
I created two pages using Page one, and Page two as titles

Page one's authored date is October 13, 2012
Page two's authored date is October 15, 2012

I enabled the PHP filter module
I created a block with the below code, and enabled it on the right side bar

module_load_include('inc', 'archive', 'archive.pages');
print archive_page('all', 2012, 10,  13);

It does display the following output where only "Page one" is the one authored on October 13, 2012.


How to insert multiple tables into their respective backup tables using insert sql? For the purpose of backup and restore i want few tables to be just backup  while performing a restore process. I have created backup tables but now whenever i do restore process it shows:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062      Duplicate entry '1' for key 'PRIMARY':

Actually both tables have same schema and same primary key so whenever it try to update it there is conflict.
Can anyone please tell me how to do it ?
One more thing can i use drupal Features to do it and if yes please let me how.

You should use
Merge Queries

a Merge query is a combination of an Insert query and an Update query.
If a given condition is met, such as a row with a given primary key
already existing, then an Update query is run. If not, an Insert query
is run.

The above is for drupal
If you are using mysql then you can use UPDATE or ON DUPLICATE KEY UPDATE


How to call image on views tpl file? I have a view in drupal 7 and I have created a template of this view. Now I need to call image here.

You need to do field level theming.

Create a template file having name like: views-view-fields--your-view-name.tpl.php
drupal_set_message('<pre>' . print_r(array_keys($fields), TRUE) . '</pre>');

see Calling a field in views-view-fields--view-name.tpl.php ---- Error


How to Display a field only once in a view How to display field only once, please find the image.

How can we show image only once in a row.

PS:

We can add as attachment with image and another one with out image, but still there will be two queries ran, that I dont want.
We can make display:block for the first one and display:none for the rest. But this will load all images.

In your view create two displays.

The first display (the display you'll be using in your site)
Add the title field only
Show 5 rows starting from 1

The second display (a block for the first item)
Add the title, image and excerpt from the body
Show only 1 row starting from 0

Save the view

Edit the second view
add a Global: View area, select the second display and (this is important!) add the field for this page only.


Can I add a "OR" on a dependecy? I'm working a on a project that needs to have one of their submodules enable but not both.

I was wondering if I can have an or statement  in the .info so the user would not enable both submodules.

The Drupal 7 documentation "Writing module .info files (Drupal 7.x)" does not talk about this.

The direct answer to your question (can you use "OR" in an .info file?) has already been provided, but the actual functional outcome you're looking for can be achieved with hook_requirements.  For instance, you might use this code in my_module.install:

function my_module_requirements($phase) {

  $requirements = array();

  if ($phase == 'install') {
      if (module_exists('submodule1') && module_exists('submodule2')) {
        $requirements['too_many_modules'] = array(
          'title' => $t('Too many modules'),
          'description' => t('You may not enable submodule1 and submodule2 simultaneously'),
          'value' => 'Too many modules',
          'severity' => REQUIREMENT_ERROR,
        );
      }
      if (!module_exists('submodule1') && !module_exists('submodule2')) {
        $requirements['not_enough_modules'] = array(
          'title' => $t('Not enough modules'),
          'description' => t('You must enable submodule1 or submodule2 (but not both)'),
          'value' => 'Not enough modules',
          'severity' => REQUIREMENT_ERROR,
        );
      }
    }

  return $requirements;
}

Further reading


Where are features displayed after they are created? I just created a feature on one site for copying to another and on the site I created the feature it doesn't appear in the list of features, and I am sure I didn't delete it.

When features are created on a site as opposed to being installed do they remain in the UI or do they have to be installed as well to appear in the site's Features UI?

Is there a module that provides a UI for managing the Features which are created on a site but not installed there?

I think its important to know that essentially, Features result in modules that capture site configuration.

Fundamental differences in D7 and D8 with what Features is designed to accomplish with configuration essentially in Core.

However, if you create a feature and "write" as opposed to "download" the UI should show your saved configuration. This section of d.o gives some detail.

You may prefer to try downloading features once they are what you want, and commit them to a git repo.  Much safer and stable working this way in my experience.


Modify node in hook_node_view() for Drupal 7 I'm trying to modify the array of content, and add an extra link.

I don't want to use the Link module; this link is going to be generated with other fields, it's something like Computed Field module (which is in developing stage for Drupal 7, and I'd rather not use it).
I don't want to just add HTML/PHP to node.tpl.php. I want this to be nice solution.

I've been trying with adding new field to $node->content. I managed to copy another field and display it once again. I was able to change label of that field, but not the link itself.

Does anyone have any idea on how to proceed?

You can do this by implementing hook_node_view.

For example:

function my_module_node_view($node, $view_mode, $langcode) {
  switch ($node->type) {
    case 'my_node_type':
      $node->content['extra_link'] = array(
          '#weight' => 10,
          '#theme' => 'link',
          '#path' => 'path_to_content',
          '#text' => t('An extra link'),
          '#options' => array(
              'attributes' => array(),
              'html' => FALSE
          ),
      );
      break;
  }
}


Views pager when view is running on Node Id I have a view with a contextual filter of Nid running to display the current node.
Does anyone know of a way to set up pagers within a view that can handle paging to  next/prev nodes? So a 'next' link for the subsequent node and a 'prev' link to show previous node.

I would normally use custom pagers for this but this module does not work properly with views 3 that I have installed.

Any help or an alternative to custom pagers would be much appreciated.

I've used Previous/Next API for this kind of situation (it's only dev, but it worked for me, YMMV).


Export Recipes from Recipe module I'm working on a site with the Recipe module for cooking recipes installed on it. According to the linked page, it's possible to import and export recipes to and from that module. Unfortunately, I can't find where that can be done. Does anybody know how to do it?

I'm fairly new to Drupal, so I'm sure I'm just overlooking something obvious...

Make sure you enabled one of the additional modules that allow you to export the content, e.g. "Recipe recipeML" or "Recipe MasterCook4". They will provide you with extra pages where you can import/export the content.

For example, "recipeML" will add new pages for importing/exporting the recipes on the following paths: admin/content/recipe/export_multi and admin/content/recipe/import_multi.
Visit admin/content, then click on "Recipes" from the list of local tasks and from there you can go to the import/export page.

Hope this makes sense.