How to customize the "Remove" button in a multiple field (collection) So, you have a field (collection, it's the same there) defined with unlimited values, and thus have an "add more" button and a row per distinct value. Let's call the field termine.

Now you have to theme the "remove" button in each row, e.g. to change the text to an imagebutton, and you wonder why your usual $form['field_termine']['und'][$k]['remove_button']['#value']="Kill"; in xxx_form_alter does not stick when adding another row via AJAX.

The solution is easy, but it took me a couple of hours wading through Drupal Core nevertheless:

foreach($form['field_termine']['und'] as $k=>$v) {
  if(!is_numeric($k)) //we only want the individual items...
    continue;
  $form['field_termine']['und'][$k]['remove_button']['#value']="Kill";
}

Note that you will get in trouble with multi-language support with this, YMMV.


How to display one block among two block in Drupal? I have two block (like Block1 and Block2) and I have to display one block among two. Condition is Block1 will be display into the whole site if Block2 is not present there. Block2 will be displayed into specific pages which is controlled dynamically, i.e. when user create content in future they can control the Block2 display. So I need to display Block1 where Block2 is not present.

I am using Durpal 7.

Note: I have tried with default block visibility but this is not worked for me either.

This sounds like you're going to need to use something like Context to toggle the display of each of the two blocks depending on the context of the page.

See this tutorial for more info on how that works.


What are the key differences between Drupal 7 and Pressflow 7? I am currently using Drupal 7.
I heard Pressflow is another solution for high performance sites.

If you have experience with both systems, what is the benefit of migrating from Drupal 7 to PressFlow 7 ? What are the major differences between D7 and Pressflow 7 ?

I dug in to find all of the differences and looked them up on GitHub and this is what I found:

Pressflow Smart Start will forward you to the install page if the database is set up in settings.php but the database is empty, disabled by default.

Files: includes/bootstrap.inc and sites/default/default.settings.php
Commits: https://github.com/pressflow/7/commit/fa91b2fc80741cb8c42c2db618f0ef0ad890f4cc

Allow for environmental PRESSFLOW_SETTINGS to override settings.php; settings must be entered as a JSON array.

Files: includes/bootstrap.inc
Commits: https://github.com/pressflow/7/commit/673fb0bdab618f8989365012149c76b8397f95d6 (Pull request: https://github.com/pressflow/7/pull/7), and https://github.com/pressflow/7/commit/953e6608b34975eaa0c8abed8a90f80d22f1b967

APC CSS and JS check; to prevent Drupal from constantly checking the file system for core-aggregated CSS and JS files, use APC as a key:value store instead. This is very helpful for networked file systems (and therefore very relevant to Pantheon, who happens to be the primary driver behind Pressflow since version 7).

Files: includes/common.inc (also see lines 3558 and 4949)
Commits: https://github.com/pressflow/7/commit/e2f9d2b10b4f0c5f61f120be145621913c6794a4 (Pull request: https://github.com/pressflow/7/pull/16/files, original pull request: https://github.com/pantheon-systems/drops-7/pull/4)

Allow modules to act on the js_cache before writing to disk, add a new hook called hook_js_cache_alter, and, if you use the new hook, add a note to the aggregated JavaScript that it was built with PressFlow

Files: includes/common.inc and modules/system/system.api.php
Commits: https://github.com/pressflow/7/commit/53098cf059236110716ca97c18565a178c458b43

Allow sub-second delays for lock_wait(). The calculation Drupal currently does will allow a value of 0 for the lock wait time, effectively skipping it. When PHP converts to an integer, a float will always round down. For example, as Drupal performs the operation: php -r "echo (int) 0.25 * 2;" would return 0. The Pressflow change corrects this, for example: php -r "echo (int) (0.25 * 2);" would return 5, allowing for sub-second delays to be used as an input to the function.

Files: includes/lock.inc
Commits: https://github.com/pressflow/7/commit/2cd4323946987608a660694df2c02f3cb4cce6c3

Here's a full diff as of October 2013: https://gist.github.com/alanthing/6064500


Fields pending deletion error when disabling comment module I tried to disable the comment module but got the following error comment: Fields pending deletion. I deleted all my comment content and fields, but the error keeps appearing and I can't disable the module. Can anyone tell me what's happening?

You probably did some batch operations or import. Running cron could solve the issue, or run the following command in drush:

drush php-eval 'field_purge_batch(1000);'

Change the '1000' value to larger numbers if you did for example an import of more nodes.


Get the value of a field inside a paragraph field in hook_preprocess_field I'm usign the module Paragraphs for Drupal 8. I need to print the raw value of a paragraph field in the twig template, so I'm trying to access to the value of the field in the hook_preprocess_field, but I don't know how to access the value in $variables.

Any idea?

You can use preprocess field hook which is supported in drupal 8 also . Example below:

function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    //get the value of the field
    dsm($variables);
   print_r($variables);
    // add a class to the field
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}


Is it possible to publish from my local computer a node in my drupal page remotely? I wonder if it is possible from a SH script on my local computer, publishing content on a remote installation of drupal.

Why have a gammu sms gateway and when a new sms on my local computer I want to be published in my drupal page.

This is an example of a script that warns of a new sms

    #!/bin/sh
INBOX=/path/to/smsd/inbox
PROGRAM=/bin/cat
for ID in "$@" ; do
    $PROGRAM < $INBOX/$ID
done

Could you do something similar to send this SMS to my remote drupal page?

Do you already know this module : https://drupal.org/project/gammu
It seems to fit your needs :

  This module support Gammu database using same or separate Drupal database, even located on different server.

And it's provide with example.

Hoping that help.


Before saving a node how to get the file path For a content type "TEST" which has a field "upload file", I want the file path before saving the node.
hook_node_presave can be used to do anything before saving the node.
I want to rename the file before it get saved into database.

but my file is getting saved first into the database.

How to do rename a file before it gets saved into database in a custom module.

Check out hook_file_presave() function.

You might have to additionally rename/move the file after it has been uploaded.

See also this thread and check the File (Field) Paths module as it might have already the functionality you need.


How to add radio button in drupal profile page I want to get more info from my users when they register.
With the standard profile.module I have the following options:

single-line textfield
multi-line textfield
checkbox
list selection
freeform list
URL
date

But I want radio buttons to select 1 option from multiple options.
This can be done with list selection, but I prefer radio buttons.

Can anyone help me with this?

By using the Profile Checkboxes module, you can be able to add radio buttons in the Drupal profile page.

Download the Profile Checkboxes module, and install it.
If you need to create a radio buttons field, click "List selection" in "Add new field."
In that page, you will find the "Selection options" option with a text area field. Enter the radio button details here. For example, if you are adding the gender, enter "Male" and in next line enter "Female."
Now, at the bottom of the page you will find the "Profile checkboxes" tab.
There you select the "Radio buttons (single choice)" and save.


Embedding a YouTube channel Recently i did small project for a community now their requirement is to include a block that contain a YouTube video frame and they have to display their YouTube channel there, So i have installed emfield module but i don't know how to implement that. Is there any suggestion like which module is comfort for these purpose ? and How to use emfield ?

As far as I know, every YT-channel has it's own embed code. Try to embed this code to your block and make sure "Full HTML" is set as text-format.

Look here as well: Embed You-Tube channel


Role expire module in drupal 7 When I assign custom role to any user here impact protection user then after its expiry date it automatically assigns role to authenticated user. How can I remove or disable that option to not automatically assigns to authenticated user. If specified date expires then user will unable to login for that specified role impact perfection user?

Authenticate user being selected won't make a difference as the expiry date is on your other role of impact protection user.

Every user by default is an authenticated user, of which you can't make expire.


Exported menu blocks to a feature module via FE block they are not created - Why? I am using menu blocks and context to create menus on a site.  I have created the menu blocks and added contexts for there use (they are working on my local dev).  I have exported the menu blocks to code using fe block and strongarm per the recommendations in Drupal.org I am doing the following after versioning the code to git and pulling it to the new server:

drush fr <feature_module>
    "Do you really want to rever variable? (y/n) y
$ Variable reverted
    "Do you really want to revert <feature_module>? (y/n) y
$ <feature_module> revert

I clear the cache, go into the new site->admin->Structure->Features-> and the variables are listed under strongarm and the menu_blocks are listed on Block settings.

But the menus are not showing on the page.  A look in blocks and the menu are not there.  It appears they weren't built.

Am I missing a step?  Please help.

Thank you in advance

You need to select also, in the feature, under strongarm, the "menu_block_ids" variable. Also make sure that the dependency to strongarm is selected. Sometimes it shows the select box but it is left unchecked.

With that the menu block should appear in the blocks page.

It will not appear in the context->edit->menu block though, and I think that is an issue. I am doing more tests before I really open it though.

----alternatively

Don't do it with fe features or strongarm, instead, just use menu block export module (go there admin/config/user-interface/menu-block/export) and proceed, just put any name and click export.

Copy the resulting code in your feature.module (make sure you put the proper name). Something like this:

function feature_name_menu_block_blocks() {
// The array key is the block delta used by menu block.
  return array(
    '23' => array( // feel free to change this to the real id of your menu block
      'parent'      => 'menu-api-menu:0',  //the module might not encapsulate string, be careful
      'title_link'  => 0,
      'admin_title' => 'title',
      'level'       => 1,
      'follow'      => '0',
      'depth'       => 0,
      'expanded'    => 1,
      'sort'        => 0,
    ),
  );
}

Just copy the menu block you want to export, you dont have to copy all of them.


Custom Validation after Custom submit How to pass the custom validation after custom submission?

I have problem in getting a variable from a custom submit handler. Actually, the custom validation must happen in the last step in order to validate correctly.

Workflow is:

1.custom submit.

2.get a value from the API.

3.pass it to custom validation.

Since the custom validation step comes first, I am unable to validate it properly.

You can use form_set_value() in your validation handler. Let's say you are retrieving a user ID from a remote API, by sending the user's name. In your form definition, you can have:

$form['user'] = array (
  '#type' => 'textfield',
  '#title' => t('User to fetch'),
);

In your validation handler, you can retrieve the value. If a value exists you save it using form_set_value, and if it doesn't, you set an error:

$remote_user_id = retrieve_uid_from_api($form_state['values']['user']);
if($remote_user_id) {
  form_set_value($form['user'], $remote_user_id);
}
else {
  form_set_error('user', t('%user does not exist in the remote API', array('%user' => $form_state['values']['user']));
}

So in your submit function, `$form_state['values']['user'] will now contain the User ID from the remote API:

$remote_user_id = $form_state['values']['user'];


Block caching issue on twig I've created a new custom module and I used Facebook SDK to retrieve the latest post from a page.
Here is my .module file:

function social_theme($existing, $type, $theme, $path){
  return array(
    'block__feed_feed' => array(
    'render element' => 'elements',
    'template' => 'block--instagram-feed',
    'base hook' => 'block'
  )
}
function social_preprocess_block(&$variables){
 if ($variables['elements']['#configuration']['id'] === 'facebook-feed'){
   $fb = new \Facebook\Facebook([
     'app_id' => {$app_id},
     'app_secret' => {$app_secret},
     'default_graph_version' => 'v2.10',
     'default_access_token' => {$app_id}.'|'.{$app_secret},
   ]);

   $request = $fb->request('GET', '/'.{$page_id}.'/posts?fields=created_time,reactions,message,comments{comment_count,like_count},likes&limit=4');
   try {
     $response = $fb->getClient()->sendRequest($request);
   } catch(Facebook\Exceptions\FacebookResponseException $e) {
     echo 'Graph returned an error: ' . $e->getMessage();
     exit;
   } catch(Facebook\Exceptions\FacebookSDKException $e) {
     echo 'Facebook SDK returned an error: ' . $e->getMessage();
     exit;
   }
   $posts = $response->getDecodedBody();
   $facebookposts = [];
   for($c=0 ;$c<$posts_no ;$c++){
     if(isset($posts['data'][$c]['reactions'])){
       $likes_count = count($posts['data'][$c]['reactions']['data']);
     }
     else{
       $likes_count = 0;
     }
     if(isset($posts['data'][$c]['comments'])){
       $comments_count = count($posts['data'][$c]['comments']['data']);
     }
     else{
       $comments_count = 0;
     }
     array_push($facebookposts,['post_text'=>$posts['data'][$c]['message'],'likes_count'=>$likes_count,'comments_count'=>$comments_count]);
   }
   $variables['elements']['#cache']['max-age'] = 0;
   $variables['fbposts'] = $facebookposts;
   $variables['likes_comments'] = $likes_comments;
 }
}

and my block plugin code:

public function build() {
  \Drupal::service('page_cache_kill_switch')->trigger();
  return array(
    '#markup' => ' ',
    '#cache' => ['max-age' => 0,],
  );
}

and this is my block template file:

{% for post in fbposts %}

{{post.post_text}}

     {{post.comments_count}}
     {{post.likes_count}}

 {% endfor %}

Now my problem is that the code is working perfectly, but when a new post is added it will not change on the website unless I clear the cache!!!
I tried to give the block '#cache' => ['max-age' => 0,] but it didn't work, I tried \Drupal::service('page_cache_kill_switch')->trigger(); on the hook_preprocess_block but id didn't work too.

What shall I do?

You have to render the content build() returns:

block.html.twig:

...

{{ content }}

Even if it's only an empty markup string. Otherwise the cache max-age can't bubble up.

A better approach would be to return from build() a custom template, which you use for the html markup instead of the block template. See https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-from-custom-module

Then you don't need a preprocess hook and caching works with the default block template.


How to compare a field value with each title values? I need to compare two field values.

Let's say I have a content type named "Specimen".
The content title is the accepted name of that specimen.
A second field, named Synonyms, can be filled by users to suggest synonyms for the accepted name.

What I need is a field validation with that kind of test :
If the synonym matches any title of that content type, then display a message (That synonym is actually an accepted name already entered in the database) and invalidate the value entered. Else, the synonym is valid and can be entered in the form.

I know Uniqueness which is a great module to compare titles between them but not between a CCK Field and each title (unless I missed something?)

I have tried to configure a test with the module Field validation but did not manage to get a nice result, even with the test "Match against a field". Maybe it was not set properly.

I guess that Rules can be my friend too but for now, I have always created very simple rules. So I would appreciate any help to build this test.

Finally, I found a solution with the module Field Validation and a PHP Code validation rule associated to my field Synonyms:

$args=array(':type'=>'specimen');
$titles=db_query('SELECT title FROM {node} WHERE type = :type',$args)->fetchCol();
foreach ($titles AS $title){
if ($this->value==$title){$this->set_error();}
}

It works like a charm.


Is there any difference or advantages between use of libraries in theme or module level with using of "Libraries API" module instead? Is there any difference between times that I define libraries in theme or module level with times that I use Libraries API module instead? Is it necessary to use library module and I add/attach my libraries to it?
What's real purpose and usage of the Libraries API module?

The real purpose of Libraries API module is to serve as a central point of information about libraries, so modules can rely on this module to request loading libraries. This avoids modules to include libraries in their module package and just ask Drupal for them.

The main advantage is it avoids conflicts and duplication between several modules shipping same library. With this module, both modules declare the need of a certain library, that should be installed in the Drupal librarires directorty.

Also, modules don't need to include code to detect and load the libraries, version detection, etc

See The ideas and design behind Libraries API 2.x for a detailed explanation.


How to install a local module file with drush? I have a local environment I am working on and I want to use drush to install a local file/module I have that was created by a exported feature. The reason I am not doing it with update manager is because its giving me a ftp error and rather than try to solve that, I would rather bypass it completely with drush (and since drush is faster anyway).

So basically I have my main site in www/var/mysite

And i have the exported feature module in my home directory / downloads.

So how do I get drush to upload and enable my local file to my drupal site?

If you already have the module / feature that you want to install on your local disk, simply copy the files to DRUPAL_ROOT/sites/all/modules.  Some folks also like to create "contrib", "custom" and "features" directories inside of "modules" to better organize their files.

Once you have your files in place, run drush en featurename to turn it on.


How can can I get theme callback to work for an error page? I've created a custom error handler for 404 errors (page not found).

I've set up Home » Administration » Configuration » System  » Error Pages for 404 errors to point to http://example.com/myerrorpage, and then I have the following in hook_menu

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items = array();
  $items['myerrorpage'] = array(
    'title' => 'myerrorpage',
    'access callback' => TRUE,
    'page callback' => 'myerror_page',
    'theme callback' => 'myerror_theme',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

When I enter a non-existing path (e.g. http://example.com/bogus) the page callback is invoked as expected.

However, the theme callback is not.

To get the  theme callback to fire, I need to enter the following path: http://example.com/myerrorpage.

I do not understand why the theme callback does not fire at the same time as the page callback.

Is there any way to get the theme callback (or hook_custom_theme()) to fire when a non-existing path is given?

In menu_get_custom_theme(), you can see that theme callback on menu router would not be called if the menu router doesn't exist. But you can achieve that with hook_custom_theme().

I'll go like this:

/**
 * Implements hook_custom_theme().
 */
function MYMODULE_custom_theme() {
  $router_item = menu_get_item();
  if (empty($router_item)) {
    return 'THEME_NAME';
  }
}


call a js function on loading a page is it possible to call a javascript(jquery) function once a particular page is loaded. It should be hacking the  of the whole site and to detect what the current page is and call the function. How can I actually do this?

So in a non-drupal php site, I would add a js file and have a start_product_content() function there. In the head.php file it would be something like this:

...
<head>
    ...
    <?php if $current_page = "product" ?>
    start_product_content()
    ...
</head>
...

I have explained in a different post about what I really want to achieve, long story: footer link to a page with hash changed content ready

I have achieved this when I was doing a non-drupal website, now I just want to be able to do this so that I can be closer to the target.

Thanks

If you want to add arbitrary code to the <head> element you need to:

Take a copy of the core html.tpl.php file and put it in your theme somewhere
Clear the caches so it gets added to the theme registry
Implement hook_preprocess_html() in your theme's template.php file like so

function MYTHEME_preprocess_html(&$vars) {
  $vars['some_var'] = 'Something';
}

In the html.tpl.php file, use

print $some_var;

wherever that might be appropriate.

If you want to add structured code to the <head> tag then use drupal_add_html_head().

Finally, specifically to add JS to the page, you can use drupal_add_js(). But that needs to happen before the HTML template is processed. hook_preprocess_page() would be one option, but there are many, depending on the context that makes up your page.

You'll find the Theming guide, and questions already asked on this site, invaluable if you're learning the theme system from scratch.


How to extend (alter) webform submit function to add more funcitionality? I have created a webform, whose id is webform_client_form_1, I have 3 fields:

  Name:
  Email:
  Phone number:

Now I want to extend webform submit function to send SMS to that Phone number. I have a working PHP script which sends SMS, using 3rd party service.

So my question is how to extend the submit function for webform? Is there any hook available or there is other method to do it?

Submit function for webform is: webform_client_form_submit

Just append your function to the #submit element to add it to the list of handlers.

MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'webform_client_form_1') {
    $form['#submit'][] = 'webform_client_form_submit';
  }
}


MySQL query for getting blog records/content Drupal7? I want to customize the and limit the content from the blog entry. If I want hook the sql query output for blog entry, How can i do it?
Please help me.

The limit is controlled through a variable called default_nodes_main. You can change it by executing the following code:

// This would increase the number of nodes on the blog page to 20.
variable_set('default_nodes_main', 20);

If you have Devel module installed, you can do this at /devel/php.


Feeds import creating more nodes instead of replacing or updating - Drupal 7 I have Feeds module, but even if I use the correct "guid" and it appears in feeds_item database table, and I configured it to "Update" (also tried "Replace") existing nodes, and "Delete" non-existing nodes, it will create more nodes, so my database is getting higher and higher Nid numbers. I am using Feeds Tamper submodule. What can be wrong?

I figured out the problem: I had not set "Guid" as unique identifier, that is the reason it was duplicating the rows in the database and why it was not replacing or updating the content. The problem now is how to reset the node->nid number to a reasonable number after all these deleted entries.


How use views exposed filters with taxonomy and panels I need some help with the use of contextual and exposed filters with taxonomy terms views using panels.

Context:

I have a panels taxonomy page overriding drupal default page.
In this page I have a views content pane display listing nodes with contextual filter set to "has taxonomy term Id" with type "taxonomy term id from URL" and "limit terms by vocabulary".
In "filter criteria" section I have a content type filter and the most relevant for my case, an exposed filter: "Content has taxonomy term", "is one of... allow multiple selection..." the usual.
4- In Pane settings: Use panel path, set to "Yes".

The idea behind this is to have a taxonomy views pane showing results with exposed filters in the panel page. I.E: The user go to "animales/aves" URL and see as expected all the nodes from a content type categorized as "aves". The problem here is when the user try to filter to another animal category. In my example, the view give me no results. The URL change from animales/aves to this: animales/aves?tid[]=1 (or other id) but allways I get an empty view, except if I select back the exposed filter for "aves".

Any help?

Drupal 7.41
Ctools 7-1.9, Panels 7-3.5, Views 7-3.13

Not sure if you did this already under the "MORE" section.


How do I limit or require the number of tags in a taxonomy reference field? Similarly to how StackExchange requires tags on a question, how can I ensure the user uses at least four tags but no more than 8?

The module field_validation has an option for Number of selections which could be what you need without custom coding. For 7, there's a full release and for 8, there's an alpha.


Display some content on selected pages My project runs on Drupal 6, and I'm using Views.

I have a main menu with two submenus (menu -> sub1 -> sub2).

This image shows what it looks like on my "edit panel."

The box with an orange border is the second submenu, and the one with a black border contains the item content assigned to this second submenu.

All the items from all submenus assigned to first submenu (main menu -> sub1 -> sub2.1, sub2.2, sub2.3 ...) are showing up already in the first submenu. (Th first submenu is a drop-down in the main menu; I don't want to have all submenus in the main menu, but just the first one.)

I want to hide them from there and display only the item that belongs to ie. sub2.1 or sub2.3. When I click sub1, I see all items from all sub2; when I click sub2.1, I see the correct items assigned to this submenu.

To understand what may be going wrong in your attempt it would help to clarify a few things about which modules do what.

Your menus are handled by either core menu or another of the menu modules that build upon it.  They display links and and any selection reroutes the browser to a new URL.
Views is a User interface to query the database in which all of your content is held.  If you select the settings tab in the main views page you can set the actual SQL query to be displayed in the preview area.  This is helpful in understanding what is being searched for in your settings, although you will need some understanding of queries to make sense of it.  A view is called either by using the defined path in the URL or by placing the view in a panel (Which you have done here).
Panels is primarily a module to handle the display of content. However, it works very closely with Page Manager module.
Page Manager intercepts URL requests and acts upon them in accordance with rules you establish for selection and contexts.  Panels and Page Manager collaborate together and switch between themselves regardless of where you start in the UI.

When you select a menu item it is requesting that the browser go to a specified URL (menu).  That URL request should be requesting the panel page (panels and page manager) which in turn is requesting the view that you have placed in it (Views). For your example, once the request  is made menus, panels and page manager are done.  Your real issue is with the views, so you must focus on the view module and your definition.

In order to help the view distinguish between various levels of content you can add a field to the content type that defines its level. You can then expose that field to views by selecting it as a filter and setting the value you want for that article.  You can create multiple view pages within the View definition to address different filter settings needed for placement in each of your panel regions. By categorizing the menu-selection/articles and providing separate view pages (within the same View definition) you can refine your control of the displayed content.

You can also limit the number of articles displayed by a view by selecting the options under pager in the view definition page and telling how many pages/articles to display.

You can learn more about Views at nodeone.se


Programatically initialising paragraph field in drupal 8 I would like to programatically populate a paragraph field with a default value for one of my content types.

I came up with the following solution:

use \Drupal\Node\NodeInterface;
use \Drupal\paragraphs\Entity\Paragraph;

function my_site_node_create(NodeInterface $node) {
    switch ($node->getType()){
        case 'my_content_type':
            $paragraph = Paragraph::create([
                'type' => 'references',  // paragraph type machine name
                'field_references_title' => [  // paragraph's field machine name
                    'value' => 'Some examples of what we have done' // body field value
                ],
            ]);
            $paragraph->save();

            $node->set('field_paragraphs_content', [
                [
                    'target_id' => $paragraph->id(),
                    'target_revision_id' => $paragraph->getRevisionId(),
                ],
            ]);
            break;
    }

}

This code seems to work but im worried I might be creating useless Paragraph-entities when the user doesn't save this node (because of the '$paragraph->save()').

How can I avoid this?

You should be able to rely on the auto-creating of new paragraphs, instead of assinging the ID, do not save the paragraph and assign it with 'entity' => $paragraph.

This should then actually save the paragraph when the node is saved.


How can I roll the database back to the backup I have a problem with a module the site functions but  I need to roll the database back to the backup I took before deploying the module. How can I do that?I am using D8

You can use Drush.

All you need to do is to run, inside a Drupal instalation, the following command:

drush sqlc < path/to/backup.sql

*You may want to drop your current database before that. The command is:

drush sql-drop -y


How do I render a Twig template and load a CSS file from a controller? Is this considered a good practice for rendering a Twig template and loading a CSS file from a controller?

DefaultController.php

namespace Drupal\acme\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Template\TwigEnvironment;

class DefaultController extends ControllerBase implements ContainerInjectionInterface
{
  /**
  * @var Drupal\Core\Template\TwigEnvironment
  */
  protected $twig;

  public function __construct(TwigEnvironment $twig)
  {
    $this->twig = $twig;
  }

  public static function create(ContainerInterface $container)
  {
    return new static(
      $container->get('twig')
    );
  }

  /**
   * hello
   * @param  string $name
   * @return string
   */
  public function hello($name)
  {

    $template = $this->twig->loadTemplate(
      drupal_get_path('module', 'acme') . '/templates/hello.html.twig'
    );

    $markup = [
      '#markup' => $template->render([ 'name' => $name ]),
      '#attached' => [ 'css' => [
          drupal_get_path('module', 'acme') . '/assets/css/acme.css'
        ]
      ]
    ];

    return drupal_render($markup);
  }
}

acme.routing.yml

acme_hello:
  path: '/acme/hello/{name}'
  defaults:
    _content: '\Drupal\acme\Controller\DefaultController::hello'
    _title: 'acme Title'
  requirements:
    _permission: 'access content'

hello.html.twig

Hello {{ name }}!

As far as I understand, the controller should just contain the following code.

class DefaultController implements ControllerInterface {
  public function hello($name) {
    $twig = $this->container->get('twig');
    $path = $this->templateDir . 'hello.html.twig';
    $template = $twig->loadTemplate($path);

    return [
      '#markup' => $template->render(['name' => $name]),
    ];
  }
}

See also Drupal 8: An Introduction to the New Production.

I still have to find a reason to do this, thought. hook_theme() is still supported by Drupal 8, and it doesn't seem it is getting deprecated, at this time. The only difference is that in Drupal 8, theme() has been renamed _theme(); as such, it should not be called directly.
Since you are asking if your code is considered good practice, I would say no: You should do as you did with Drupal 7, defining a theme function in hook_theme() that uses a template. Then return markup similar to the following one in your controller method.

[
  '#theme' => $your_theme_function,
  '#name' => $name,
];

Replace $your_theme_function with the theme function ID, and #name with the array index used for 'variables'.
Actually, there is a difference between Drupal 7 and Drupal 8: While Drupal 7 allows you to attach JavaScript and CSS, Drupal 8 allows you to attach just libraries, which are a set of JavaScript and CSS files with dependencies.


if term reference is value X in tpl.php file I want it so that in my page.tpl.php file if the user has selected "Standard" as the "Page Type" term reference it prints an extra bit of html.

I tried something along the lines of the code below but have not had any luck so any help would be greatly appreciated.

<?php $page_type = field_get_items('node', $node, 'field_page_type');
if ($page_type == 'Standard') {
    print "worked";
} ?>

If I print the "field_page_type" value further down the page it prints "Standard" on the page but if I use the if statement above it doesn't print the "worked" result.

I am using Drupal 7.

The above use of field_get_items('node', $node, 'field_page_type'); is going to return an array that looks like:

Array
(
    [0] => Array
        (
            [tid] => 549
        )

)

But what you want is the value of the term so you'll need to do the following:

<?php $page_type = field_view_field('node', $node, 'field_search_type');
if ($page_type['#items'][0]['taxonomy_term']->name == 'Standard') {
    print "worked";
} ?>


How can I embed a webform in an Ionic React app? Webform has a Share submodule that can be used in decoupled situations.
There is a video tutorial here.
However, I'm having trouble getting my webform embedded in my Ionic React app.
What I have done

Went to /admin/structure/webform/config and selected Enable form sharing under Form share settings.
Went to /admin/structure/webform, clicked the more info triangle, selected Share.

I now have the option to choose from JavaScript, Resizing iframe, and Fixed iframe, but all of these use document.write, which won't work with Ionic because the document has already been written.

Here is specifically how to do this in Ionic + React.
First, Webform share uses the iframe-resizer library, which has an official react component.
So install the library into your app:
npm install iframe-resizer-react
Then add a component such as WebformContact.tsx (this example uses TypeScript):
import * as React from 'react';
import {
  IonContent, IonPage,
} from '@ionic/react';
import IframeResizer from 'iframe-resizer-react';

const styleWebformIframeEmbed: React.CSSProperties = {
  width: '1px',
  minWidth: '100%',
};

const WebformContact = () => (
  <IonPage>
    <IonContent>
      <IframeResizer
        src="https://example.com/webform/MY-WEBFORM-MACHINENAME/share/iframe-resizer/4.2.10"
        title="MY WEBFORM TITLE"
        frameBorder="0"
        allowFullScreen
        style={styleWebformIframeEmbed}
      />
    </IonContent>
  </IonPage>
);
export default WebformContact;

Note that you need to install the same version of iframe-resizer in both webform (drupal) + your ionic app.
Also note that if your site is https, you should be sure to specify that in the src tag; when React is hosted by Ionic, it will be run from http://localhost (Android) or http://capacitor (iOS), so if you do not specify https for the server, you will get a difficult to understand error:

iframeResizer.js:822 Failed to execute 'postMessage' on 'DOMWindow':
The target origin provided

But really what this means is that you are trying to access an https server in an iframe with http.  So specify https!


TB Megamenu - How can I reuse a menu with different megamenu configuration? I have a Drupal core menu setup for my main menu that has > 50 links setup.  I've also got TB Megamenu configured for that menu to show the menus with pictures, etc.

Now I have a case in which I want to show the same menu content, but configured differently (to shown only standard flyouts with no images) on all pages but the home page.

I haven't been able to find a way to do this without duplicating the main menu link by link (which I obviously don't find sustainable).

Can anyone think of a way I could accomplish this?

(Note that I did try the Context module, which is great, but is not really suited for this purpose).

Thanks.

You can use Superfish module and reuse same main menu . All you need to do is configure super fish menu block with main menu.

Project page says

"Multi-column sub-menus. (Megamenus)
Easing effects with the jQuery Easing plug-in, and many more...."


Panels cache terminology- what's the difference between caching by argument vs. by context? I'm trying to learn how to set up Panels caching.  I watched a video on mastering Drupal caching and I have the book by Earl Miles on Panels and Views, Drupal's Building Blocks, but unfortunately there's not a chapter specifically on caching.

So, I have a panel that overrides the user profile, and on this panel I have a variant that has a number of views content panes.  I would like to cache these content panes per user profile displayed, since obviously they should be different for each user who is viewed.

Each of these content panes has a Contextual filter on Content: Author UID.

The value is supplied to Panels by the Argument input option in Views, for which the Content: Author uid source is set to From context and Required context is set to User ID:

In Panels, on the Simple cache configuration screen, for the Granularity, I can choose Argument or Context, and the help text is this:

  If "arguments" are selected, this content will be cached per
  individual argument to the entire display; if "contexts" are selected,
  this content will be cached per unique context in the pane or display;
  if "neither" there will be only one cache for this pane.

But in Views, the option is called argument input and the value I chose was from context.  So am I dealing with an argument or a context?

If possible, both a general answer describing the difference between argument and context in this case and a specific answer to my question would be fantastic.

Disclaimer: I usually find that the setup is simple enough that the distinction isn't necessary, thus I must admit my practical experience is limited, and I could be wrong below.

Arguments, are based on the URL. node/5 gets cached separately from node/7, because 5 is different from 7. node/5/7, if you where to have such a path, is yet another cache.

Contexts, are generally derived from Arguments, and in the examples above, it's very likely that the caches would be exactly the same, regardless of which cache option one would pick. However, Contexts, can also come from (at least) three other sources, Relationships, manually defined ones, and the special case, the logged in user.

If your context is both a node from the URL, and a user pulled from an entity reference on the node, then your context has two unique entities, or two contexts, but only one argument.

So one chooses Context or Argument depending on whether you want the cache to take any "extra" contexts into question, or not.

  But in Views, the option is called argument input and the value I chose was from context. So am I dealing with an argument or a context?

Unfortunately the terminology isn't exactly the same between the two modules. Panels calls dynamic pieces of the URL arguments, and it creates contexts from those. Views, means something closer to a function argument, when it refers to arguments, and in this particular case, it will derive the argument from a context, passed in by Panels.


Limit Fivestar for node author only I have a content type called Task, where I add tasks. After task being completed, I would like the node author to rate his satisfaction using Fivestar field.

While viewing the node (not in edit mode), how to enable voting on this satisfaction rating field by node author only on his task but others can't vote, they can see his/her vote.

Here are the steps you need to allow only the node author to rate the node.

For the Task content type, change the role permissions so that only the authenticated users (or whichever role you want to allow to complete and rate Tasks) have the "Edit own content" permission.
Under "Manage Fields" for the Task content-type, configure your rating/fivestar field to use the widget "Stars (rated while editing)". Now, only the node's autor can edit and rate a Task node. The vote will still be visible to other users.

Hope this helps!


Main navigiation layout bugs after adding a cart block I have a question about some layout problems that I'm having since I installed commerce 2.x on my school project website. I'm using Drupal 8 for this.

You can see that one of the dots between each menu item are gone and another dot is slightly misplaced. Is there a way to restore this or remove all the dots maybe? The domain of my website is designmuseum.vansompel.be

I have been changing some of the css in the most upper sidebar to get the cart block next to the user account menu. Even when I revert these changes, the problem on the main navigation seems to remain.
Could it be that my website is doing some automatic layout tweaks because of the new cart block? For example there is also a 10px padding above the cart block that I didn't specify myself and can't seem to find it in the code also.

.header-top-highlighted__section .block + .block {
  padding: 10px 0 0 0;
}

I'm still pretty nooby at theming so if someone could point me in the right direction, that would be great! Thanks!

Looks like those dots are a content on :before of the anchor tag, to remove them you could add this to your CSS files.

.header-container ul.menu li a:before {
    display: none;
}

This looks like it have been added by Drupal or maybe the theme you are using, i am not really sure, I recommend you read this https://www.w3schools.com/cssref/sel_before.asp to understand more about the before selector.


Importing Taxonomy from CSV I know that there are a couple of modules to import taxonomy from CSV but my taxonomy has many term references inside it.

Attached is a screenshot of my taxonomy, how can I import the excel sheet into it? Please help

excel sheet.

Programmatically speaking, for term references you need to use the Term ID rather than the actual term name.

Luckily, the D7 Feeds module comes with a feature where it fetches the Term ID automatically for you based on the Term Name.

Here is an example of one of my mappings:


How do you alter a form error? How do you alter or remove a form error produced by Drupal or another module on node insert/save, for a particular content type. I'm looking for a method which I can use in a module.

I've tried hook_node_validate(), but all I was able to do is to get errors and set errors.

Altering strings

To change the text of a single string, the simplest method is to use the String Overrides module. That would allow you to replace the string:

  "!name field is required."

with (for example):

  "The field '!name' is required."

Altering form fields

If you want to make a field not required, use a normal hook_form_alter() implementation:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form['#node'];
  if ($node->type == 'my_custom_type') {
    $form['title']['#required'] = FALSE;
  }
}

Changing the way a form is validated

Forms have validation functions specified in the $form['#validate'] array. And form elements have functions specified in $form['element_key']['#element_validate'].

You can specify your own like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $form['title']['#element_validate'][] = 'mymodule_validate_node_title';
}

/**
 * Validate the node title to prevent ALL CAPS.
 */
function mymodule_validate_node_title($element, &$form_state, $form) {
  if (preg_match('/^[A-Z]+$/', $element['#value'])) {
    form_error($element, t('You may not enter titles in ALL CAPS.'));
  }
}


Change the current loggedin Domain? At D7 multi-domain site, how to simply change the current domain of the user after he logged in to another domain?

For e.g,
A user fill the login form at, "false.example.com", I want to push him into "true.example.com"
I believe it is the SESSION trick.

Note: I'm using the "Domain Access" module at D7.

It depends on your settings.php $cookie_domain value.

/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on on its full domain name. If you have multiple domains pointing at
 * the same Drupal site, you can either redirect them all to a single domain
 * (see comment in .htaccess), or uncomment the line below and specify their
 * shared base domain. Doing so assures that users remain logged in as they
 * cross between your various domains.
 */
# $cookie_domain = 'example.com';

For the session cookie, a value of:

$cookie_domain = '.example.com'; // Note the leading wildcard dot "."

will work across subdomains

Whereas a value of:

$cookie_domain = 'true.example.com';

will only work on true.example.com

If that session id is valid for that site database session table then the user will be logged in.


Can not find the price of products in ubercart tables I need to export products from Ubercart, the problem I am facing is the price of products is shown 0.000 in uc_products in all related fields (list_price, cost, sell_price) for almost every product but on admin side and front end every product has price more than 0.000.

my question is Where else the price could be store in ubercart tables other than uc_products?

Any where in cache tables, attribute wise or somewhere else?

I dont know what modules are installed on the site. But prices were in different tables for different currencies, found them finally

content_field_price_usd
content_field_price_eur


Field permissions per content type? I have a video field that should be visible only to authenticated users on one content type (bundle), but unrestricted on another content type.

What's a clean way to hide this field on one content type only, for anonymous users?

Notes:

I have the module field permissions installed, but it doesn't support per bundle field permissions.
I'm using Display Suite, so I'd rather not use a custom template unless that's the cleanest way to handle this one field.
I could create a new view mode that hides this field and and use HOOK_entity_view_mode_alter to switch to that view mode for anonymous users, but there are quite a lot fields to display so having 2 big view modes that are 95% the same seems kind of silly.

Edit: This is the code I used based on @wolverine's answer below:

function HOOK_utility_field_access($op, $field, $entity_type, $entity, $account) {

  //Check video field only when attached to 'lesson'.
  if ($field['field_name'] == 'field_video' && $entity_type == 'node' && $op == 'view' && $entity->type == 'lesson') {

    //Grant access only if user is logged in.
    if ($account->uid > 0) {
      return TRUE;
    }
    return FALSE;
  }
}

Since you want to do it for few fields, I would suggest to do it using custom code rather than any module.

You can implement hook_field_access($op, $field, $entity_type, $entity, $account) and check for the "field name, content type, user, operation" and then  deny or allow access.


Is it possible to cancel a delete request for a node or media item? I am trying to create a soft delete method and I was hoping to manipulate cores delete method. The plan was to set a flag on the entity to say that it had been deleted and gets moved to a new page for approval before permanently being deleted.

I am aware there are several contrib modules out there but they are either only in beta or don't quite do what I wanted.

I have been trying to use hook_entity_pre_delete() to set this flag, but I am unable to then cancel the request to delete the entity.

Does anyone have any bright ideas?

Have you considered the new Content Moderation module in core? It should provide the desired functionality.


"Notice undefined index" for an existing element in $form array Basically This is my Array

 array(
        [product_id] => Array
        (
         [#type] => hidden
         [#value] => 39
        )
      )

and I am trying to get the value which is '39'

$cartId = $form['product_id']['#value'];

and yes I get the value without any issues, but in my site it gives me a notice saying "Notice: Undefined index: product_id in  ..."

This is my entire code

function MyModule_form_alter( &$form, $form_state, $form_id )
{
    $cartId = $form['product_id']['#value'];
    print_r ($form['#value']);
    if ($form_id == 'commerce_cart_add_to_cart_form_'.$cartId)
    {
        $form['add_to_wishlist']['#weight']= 49;
    }
}

any ideas how to fix this? because I couldn't figure the cause of it as it works well!

Your function is called for all forms in your Drupal. $cartId = $form['product_id']['#value']; is called outside if, so it's also executed on all forms. And most of them does not have $form['product_id'] defined at all. Move that part inside if block.


ACL, Node, and User exists in DB, but still no access Trying to write a custom module tying in ACL with commerce_license (to purchase access to content), but I'm not sure I'm implementing the ACL API correctly. Everything seams to be in the database, however. I'm probably missing a step, but I'm not sure what that is.

User is uid 3. Node I'm trying to access is node/23. ACL is 16.

ACL is listed in acl table. Node is listed in acl_node table, with grant view only. User is listed in acl_user table.

mysql> select * from acl WHERE acl_id = 16;
+--------+----------------------+-----------+--------+
| acl_id | module               | name      | number |
+--------+----------------------+-----------+--------+
|     16 | commerce_license_acl | ACL_4_23  |   NULL |
+--------+----------------------+-----------+--------+

mysql> select * from acl_node WHERE acl_id = 16;
+--------+-----+------------+--------------+--------------+----------+
| acl_id | nid | grant_view | grant_update | grant_delete | priority |
+--------+-----+------------+--------------+--------------+----------+
|     16 |  23 |          1 |            0 |            0 |        0 |
+--------+-----+------------+--------------+--------------+----------+

mysql> select * from acl_user WHERE acl_id = 16;
+--------+-----+
| acl_id | uid |
+--------+-----+
|     16 |   3 |
+--------+-----+

I've noticed that in the modules that use ACL, there are calls to "node_access_acquire_grants($node)" after the calls to  acl_create_acl($module_name, $acl_name), acl_add_user($acl_id, $uid), and acl_node_add_acl($nid, $acl_id, $read, $update, $delete, $priority), so I've added that, too. However, I'm still missing something. The acl data seems to be being recorded, but the node access records are not. I'm using content_access (which also uses the acl module), but not getting the behavior I want.

What am I missing?

The issue that I was having was that my module didn't correctly implement one of ACL's hooks, [module_name]_enabled().

Prior to returning the grants, acl_node_access_records() checks to see if the module is enabled by firing off that hook, and does nothing if it doesn't exist.


Repeating text field on user profile In the user profiles, I would like to have an education field grouping. In this grouping I'd like to have these text fields.

Degree: BS/BA, MA/MS, PhD, Post Doc, etc
University
Year Graduated
Area of Study

Now, my users will have multiple degrees and such.

Can I create a "repeating" group of these four fields from 0 to infinity?

If you're working in Drupal 7, check out the Field Groups Module.

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

If you're on Drupal 6, you want the MultiGroup module, which is a part of the 3.x branch of CCK.


Print a PNG icon instead of field label I needed to print a png icon instead of field label in views, so i'm posting this question and it's propper detail answer as well, in my case i need to print whatsapp icon  as a label in a field in views, this answer is based on this post, this question is flaged as closed being off-topic, but I think it may be usefull to others. this is working in D7, it may work on D8.

First, you need a png image (my case 17x17 px whatsapp.png), place it under sub-theme/images folder, then, place this css under sub-theme/css/custom.css file

.whatsappwrapper {background-
 image:url("../images/whatsapp.png");background-repeat:no-repeat;}
.whatsapplabel {display: none;}
.whatsappnumber {margin-left: 20px;}

then, set your views field styles as shown in picture
first part of image is the result of this settings. note: telephone icon is a html symbol.


Taxonomy and menu links I have an example content type "Cars" and two vocabularies: "Country" with some terms of countries and "Brand" with some terms of brands.

The content type will have three more field that will be term references: Country, Brand and Type of cars.

I'm using a view page with path /cars that displays all the contents from that content type. The "Country" and "Brand" I'm using them as a exposed filters.

So my goal is to create a menu links from the left sidebar with type of cars like Hatchbacks, sports cars, city cars... etc. and will display the number how many cars are hatchbacks, how many sports cars....

When a user click on some of the menu links from left like for an example "Hatchbacks" it will display all the hatchbacks. And after that the filters Country and Brand will stay so a user can filter them.

My question is how can I create such menu links and will display the numbers of the nodes?

I'm using Drupal 7.

I used the taxonomy menu module on my latest project for this purpose, works like a champ!
Here is a quote about it (from the module's project page):

Transforms your taxonomy vocabularies into menus with ease!
Features:

Custom Menu per vocabulary
Uses the default taxonomy term path or custom paths
Integrate with Views
Integrate with Pathauto: use URL/path aliases
Does not interfere with other menu modules


How can I set the language of nodes in bulk to existing content when making a site multilingual? I'm making an existing site with a few thousand nodes multiligual. Source is English. How can I set all of the existing content to langauge:English instead of neutral all in one bulk command?

Here's one way to do this that doesn't involve writing any code.

Install the VBO module.
Create a new view showing Content of whatever content types you need to convert.  Use the Fields display method.
Add a field Bulk operations: content.
Check Modify entity values and select Language.
Choose Apply.
Save the view (add any other filters if necessary to limit the selection) and go to the created view page.
From the view page, choose the option to select all items on all pages and execute the Modify entity values action.
Choose the language and click next.

If you have an extremely large number of nodes, you may need to play around with the queuing settings so that not everything is executed at once, but I would try doing it in one pass first because hey, if it works, you're done (note: always test on a backup first!)


Drupal installation profile: menu_link_save() doesn't work for "import" path In my installation profile, I am trying to add a menu link for the /import path (from feed_import module). menu_link_save() works for all my menu paths with the exception of /import. Anyone have ideas why?

So, this works and creates a menu path to /user:

$link = array('menu_name' => 'menu-authenticated', 'link_path' => 'user', 'link_title' => 'Account');
menu_link_save($link);

But this does not:

$link = array('menu_name' => 'menu-authenticated', 'link_path' => 'import', 'link_title' => 'Import');
menu_link_save($link);

After installation is finished, /import path works (feeds_import is installed and enabled in the installation profile), but the menu link was not created.

Any help would be much appreciated. Thanks!

As tvl advised, "import" path is not yet defined in when MYPROFILE_install() is called in MYPROFILE.install. So moved the code over to MYPROFILE.profile and used hook_install_tasks() as explained here: https://www.drupal.org/node/1022020

/**
 * Implements hook_install_tasks().
 */
function MYPROFILE_install_tasks($install_state) {
  $tasks['add_import_link'] = array(
    'display_name' => st('Adds import link to menu-administrator'),
    'display' => TRUE,
    'type' => 'normal',
    'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
    'function' => 'callback_add_import_link',
  );

  return $tasks;
}

function callback_add_import_link() {
  // Add the menu link
  $link = array('menu_name' => 'menu-administrator', 'link_path' => 'import', 'link_title' => 'Import', 'weight' => 5);
  menu_link_save($link);
  menu_rebuild();
}


I can't set a data value using rule on a custom entity I have created a custom entity "Project" with this fields: id, name.

I have created a rule and added an action "create entity" and selected "Project".

I have added another action "Set a data value" and selected "name" of the newly created entity project and I had this message : "The selected data property doesn't support writing."

Here is the entity property info

 /**
 * Implements hook_entity_property_info().
 */
function project_entity_property_info() {

  $info = array();

  $info['project']['properties']['id'] = array(
    'label' => t('Project ID'),
    'description' => t('The ID of the project.'),
    'type' => 'integer',
    'schema field' => 'id',
  );

  $info['project']['properties']['name'] = array(
    'label' => t('Project name'),
    'description' => t('Name of the project.'),
    'type' => 'text',
    'schema field' => 'name',
  );
  $info['project']['properties']['description'] = array(
    'label' => t('Project description'),
    'description' => t('Description of the project.'),
    'type' => 'text',
    'schema field' => 'description',
  );
  $info['project']['properties']['deadline'] = array(
    'label' => t('Deadline'),
    'description' => t('Project deadline.'),
    'type' => 'date',
    'schema field' => 'deadline',
  );

  return $info;
}

In the provided hook, You need to add the setter callback.

So it will be like:

function project_entity_property_info() {
  // .... rest of code removed for brevity.

  $info['project']['properties']['name'] = array(
    'label' => t('Project name'),
    'description' => t('Name of the project.'),
    'type' => 'text',
    'schema field' => 'name',
    'setter callback' => 'entity_property_verbatim_set', // -> this is it!
  );

Now rules knows how to set the value on entity.

More information about the hook_entity_property_info can be found here. If name requires a complex workflow to be set, you can write your own setter similar to entity_property_verbatim_set (for validating purposes, or ...).

If you are benefiting from the power of Entity API you may declare it in your EntityMetadataController class. There is a default class called EntityDefaultMetadataController you can extend it and introduce it as your entity type's metadata controller.

Another option is to use entityspice to declare your entity type which takes care of it all.


using hook_query_alter with fieldcondition() I want to use hook_query_alter to alter a query constructed by a module. This is the code I use:

function MYMODULE_query_alter($query) {
  if ($query->hasTag('agent')) {
    $query->fieldCondition('field_area', 'tid', 10, '=');
  }
}

The code above gives a 500 error: Call to undefined method SelectQuery::fieldCondition()

What is the proper way to add a field condition to the query?

This was solved using the $query->innerJoin()


Why is my Twig Override not displaying any content, when the original Twig was barely different and worked just fine? I'm overriding a Twig template for the responsive_menu module, and encountering an issue with content not displaying.

The original Twig is named responsive-menu-horizontal.html.twig and my replacement is named block--responsive-menu-horizontal-menu.html.twig. Please note that the name of the replacement was derived from my Inspect Element debugger's suggestions.

The two Twig pages are almost exactly the same, save for the names and the added classes for the ul and li pieces

![1]: https://i.stack.imgur.com/T25DZ.png

When I use my override for the default Twig page, the nav completely disappears, and my debugger leaves me with this:

<!-- BEGIN OUTPUT from 'themes/indyres/templates/block/block--responsive-menu-horizontal-menu.html.twig' -->
<!-- END OUTPUT from 'themes/indyres/templates/block/block--responsive-menu-horizontal-menu.html.twig' -->

I'm confounded as to how it'll read my overriding template and render nothing. Any help/explanation is greatly appreciated, this is the first Drupal project I've ever worked on, and though I managed to keep my head above water in creating the styles for the rest of the site, this piece has me really lost.

After a lot of frustration, and realizing that I could (in fact) manage to get Superfish to do what I had originally wanted, I just composer remove'd the module and that's where it'll stay. Thanks for the help everybody!


WYSIWYG editor not actually able to make use of all its tools I've enabled my WYSIWYG editor for my authors on my site so that it uses filtered HTML format (using better formats module to ensure they use that text format).

However, while testing I note that when I use the WYSIWYG editor to input content, like new lines, tables, etc...the formatting doesn't actually 'take'. Certain things like links get set ok and bolded items...but not all the tools available in the CK editor WYSIWYG are showing correctly when the item is unpublished or published. When I go back to edit the item the HTML is all still there...but for some reason it doesn't display as if it's using the HTMl.

Thoughts on this?

Filtered HTML format restrict some HTML tags, inspect or check source code of your text and see what is new line converted to.

Few guidelines for WYSIWYG editor:

Try Full HTML format
Check with permission on HTML profiles, on this path: admin/config/content/formats
Check your jQuery version, use jQuery update module
Check is there any JS error on console


How to set up an email notification if a user gets a new role? I'm on d7. I want to notify users if they have received a new role. Any suggestions on how can I do this? Thanks.

I suppose this is for manually promoting a user. I would try creating a rule using the Rules module for modifying the role and sending a mail to the user about his/her new role on the site.

I'm still learning how to use Rules, so I won't be able to give you a detailed recipe here, but after watching the excellent Rules screencast series at the NodeOne site, you might be able to do this quickly without making a custom module.


Creating an image upload input field I'm creating a image upload input field in blockForm which will output to Twig later. But got stuck due to some stuff.

public function blockForm($form, FormStateInterface $form_state){
        $form['image_file'] = [
            '#type' => 'managed_file',
            '#title' => $this->t('Upload Your Image'),
            '#default_value' => (isset($this->configuration['image_file']) ? $this->configuration['image_file'] : ""),
            '#weight' => '1',
            '#upload_location' => 'public://',
            '#upload_validators' => [
                'file_validate_extensions' => ['gif png jpg jpeg'],
            ],
        ];

       return $form;
    }

First thing is the '#upload_location', there are a lot of different answer online and the only difference is the path after public://, so I want to know what should I actually deal with it.

Second is the use, is there something missing or it is enough for achieve my goal.

The code I have now:

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormBuilder;
use Drupal\Core\Link;
use Drupal\image\Entity\ImageStyle;
use Drupal\paragraphs\Entity\Paragraph;

Hope someone can answer and help. Many Thanks.

As i understand you could use something like this '#type' => 'file'

  $form['image_file']=array(
    '#type' => 'file',
   '#title' => t('Upload YourImage'),
    '#upload_validators' => array(
    'file_validate_extensions' => array('gif'),),

        );
return $form;


Displaying parse errors in module development on the browser I am currently trying to learn Drupal Module development.

As one might guess, many errors get created in the process. But, all i can see is WSOD on the browser.

For the same errors, most of the Module development videos on youtube show display the errors on the browser itself in an easy to understand format with specific details on the parse error(attached image).

I have tried some solutions on configuring on index.php, but in vain. Also, I can see the errors on Drush, but that doesn't satiate

Could anyone please tell me on how i can have this in my environment?

I'm running Drupal 7 on Windows 8 using Bitnami WAMP Stack.

You have to enable error displaying in PHP. There are several ways to do it, but one of the most straightforward is to enable them in the settings.php of your project.

Just add those lines to the file:

error_reporting(E_ALL);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Meaning:

Instruct PHP to notify all errors.
Instructs Drupal to show all errors (using a drupal_set_message).
Instruct PHP to display errors instead of show a blank page.
Instruct PHP to display errors even those in the startup phase.

Also, as Clive comments, if you enable XDebug error reporting is more verbose. The screenshot you show includes XDdebug error backtrace.


Wide blog theme for drupal I've been searching internet for paid or free drupal themes that is best for blogs and does have wide space for html context, not center of screen with a very tight space.

Tight space example:
http://envato.tabvn.com/demo.php?theme=aqua
responsive-blog for drupal

As you can see, they are simply wasting whole html area space and using only middle of it.

In fact, I want something like this:
http://fumalwareanalysis.blogspot.com/p/malware-analysis-tutorials-reverse.html

I'm currently using free Best Responsive. Also it should work properly in mobile devices and ipad, so if browser is mobile device, resize it or fit the page etc.
Any good example theme for drupal?

You could modify Best Responsive theme enlarging the page width. More precisely changing #wrap ID width from 960px to something bigger, like 1200px or a percentual value like 90%.

You can edit the style.css file and change the width from:

#wrap {
  width: 960px;
  margin: 0 auto;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

to:

#wrap {
  width: 90%;
  margin: 0 auto;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

You'll have to update some other elements width like #content and #sidebar using a percentual value and fix the sidebar background image.

Anyway the theme can easily be customized.

In this way the template is still responsive but on desktop the size is more wide.

I hope this will help.

Regards.


How to denote a user as a "system account"? In the Unix world, there are "user accounts" for humans to use, and there are "system accounts" for software to use.

On a Drupal site, I have a couple of system accounts intended for use by services.module API calls.

I'd like these accounts to be able to log in via the services API (obviously), but I would like to block these accounts from being used to log in via the standard user_login form.  I'd also like to prevent these accounts from showing up in standard "active user" lists, such as the "Who's online" block.

How should I approach this?

Have you had a look at using the API key authentication? This will enable you to login effectively without using a username + password combo.

See http://drupal.org/node/762092 for more information


Commerce/Rules - Multiply the price by a custom field value In my Drupal Commerce store, I have a field called Commission.

The Commission is input as a percentage (i.e. its not a fixed global value).

I need the final price to be updated so it incorporates the commission. I then need VAT to be added to the commission (but not the original price). The user should be able to see the full price (with commission and commission-VAT) before they add a product to cart.

I thought Rules would be perfect for this situation, especially as it has an action called "Multiply the unit price by some amount". However, this action doesn't seem to accept values from custom fields, even if you bring them into scope in the conditions area of the Rule.

I have watched Randy Fey's excellent tutorials on the Rules and Commercial modules, and I have tried to adapt them to my use case. However, I can't get it to work.

Could some one give me some pointers. Thanks!

I found the solution to this, so I thought I would post it to help anyone else out who is struggling:

1) Before you can call your field under actions, you have to bring it "into scope" under conditions.
Select "Entity has field". Under data selectors choose "commerce-product (saved commerce product).

2) For some reason, it seems impossible to use the "Multiple the Unit Amount by" option, as no matter what data selector you use, you will get an error.
Instead select "Calculate a value"

3) Under "Input Value 1" select "commerce-product:commerce-price:amount".

4) Select which calculation to use. In my use case, I used multiply (*).

5) Under "Input Value 2" click the "switch to data selection button". You can now select your custom field. It will be located under "commerce-product: (saved commerce product)"

6) Under "Provided variables" give the result of the calculation a name. Choose a good name, as you will be using it later on.

7) Now create a new action called "Set a data value".

8) For the data select pick "commerce-product:commerce-price:amount"

9) Finally, under value, click the "switch to data selection button". You can now select the variable you created in step 6.

This is everything you need to change the price based on the value of a custom field.

Notes:
1) For the event, I used "Before saving a commerce product"
2) I would recommend creating a custom field called "base price", where the user can enter the price before calculations. The rule is applied every time a product is saved, so the commerce price field will keep on changing each time the product is saved. If you use a base price field, you can avoid this problem.


Image uploading button is not appearing for authenticated users,only for admin When using Filtered HTML on a body text, the image uploading button is only appearing for admin users under Tinymce, but not for authenticated users.

How can I fix that?

I just had the same issue and this is what I found to fix it.

If you have IMCE to control your file browser you must create a profile for each user role. For example, the website administrator (owner of the website) will have access to the file browser no matter what, but if you have another authenticated user with the administrator role, they will not have access to the file browser unless you add a profile to the administrator role. So to do this go to 'admin/config/media/imce' or if you would prefer the interface way, log in as administrator and click on "Configuration" -> "Media" -> "IMCE".

Create a new profile by clicking on "Add New Profile" link and configure the profile to your needs. Save the profile.

Then next to the administrator role (or whatever role you need this for), select that profile you just created and click save.

Now test on a sample administrator (or whatever role you configured) account.


use taxonomy terms as values for radio buttons by code I've built a function for select / checkboxes but I can't get it working for radio buttons.

/**
 * helper function to get taxonomy term options for select widget
 * @arguments
 * @return array of select options for form
 */
function popover_get_tax_term_options($machine_name){
    //$options = array( '0' => '');

    $vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;

    $options_source = taxonomy_get_tree($vid);

    foreach($options_source as $item ) {
        $key = $item->tid;
        $value = $item->name;
        $options[$key] = $value;
    }

    return $options;
}

Calling this in a form hook works with: ( shows all terms )

$form['third']['field_functioncat'] = array(
    '#type' => 'checkboxes',
    '#title' => 'Functiecategorie',
    '#options' => popover_get_tax_term_options('functie_categorie'),
);

But when I call it with radio it doesn't work: ( only shows the title with 1 radio button )

 $form['third']['field_functioncat'] = array(
    '#type' => 'radio',
    '#title' => 'Functiecategorie',
    '#options' => popover_get_tax_term_options('functie_categorie'),
  );

#options

values must be in array: http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options

example:

'#options' => array(
            0 => t('None'),
            1 => t('Team'),
            2 => t('Business'),
            3 => t('Talent'),
        ),


Alter Fieldable Panels Pane form Im using Panopoly, and have created a new Fieldable Panels Pane (FPP) bundle for a specific content type.

I notice that all preset Panopoly FPP's have a check box labelled 'Make title a link' inside a fieldset called 'General Options', which is also automatically added to my new bundle, and I can't for the life of me work out how to disable it!

For reference, this field is visible through the Panels IPE as well as the traditional /admin/structure/fieldable-panels-panes/manage/BUNDLE-NAME/add.

Does anyone know how I can isolate and disable this option on a per-bundle level?

Thanks!

Almost all Drupal forms can be edited using hook_form_alter(), specifying the form using its id:

Hide "Make title a link" for all fieldable panels panes:

/**
 * Implements hook_form_alter().
 *
 * Simplify form for fpp.
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'fieldable_panels_panes_fieldable_panels_pane_content_type_edit_form') {
    $form['link']['#access'] = FALSE;
  }
}

Hide "Make title a link" for all fieldable panels panes of the type "your_bundle":

/**
 * Implements hook_form_alter().
 *
 * Simplify form for 'your_bundle' fpp.
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'fieldable_panels_panes_fieldable_panels_pane_content_type_edit_form') {
    if ($form['#bundle'] == 'your_bundle') {
      $form['link']['#access'] = FALSE;
    }
  }
}


Search Drupal from an external application What I want to do is use the built in search engine I currently have running in my Drupal site, but allow another site to use that same search engine.  Basically a legit copy and paste of the form code.

The reason being is I have a separate web application that is running and I am copying the exact look and feel of the Drupal site to make it seem as if the web application is part of the web site.  It's separate because the functionality would be a pain to implement in Drupal, and I could do it in Rails in 30 minutes.

So, what things do I need to configure in Drupal and in my web application to make this happen?

EDIT:  Just to clarify, my external web application is not consuming any data from Drupal what-so-ever.  All I want to do is POST the "copied" search form to the Drupal engine and have it render the search results as if you had searched directly from the Drupal site.  It seems like the Services module is used to streamline data to external web applications, and that is not the workflow here at all.

EXAMPLE: Say I have my Rails application sitting at http://app.hostname.com/ and my Drupal site sitting at http://hostname.com/.  There is a search form at the root of my Rails application that is pretty much a copy paste of the browser code you'd see as if you had looked at the Drupal site source of the search form.  It's just a simple text box with a submit button.  When I submit that form from the Rails site, I want it to POST the data to the Drupal site and have the returned results be the exact same as if I had searched from the Drupal site directly (I said this already but it doesn't hurt to re-iterate), leaving the URL bar now saying http://hostname.com/search/node/foo%20bar.

Drupal searches can just be normal GET requests w/o going through the form.  Try it.

Make a page in your RoR app to catch the POST and parse the search needle.  Then 302 to the Drupal site with the proper URL.


How to create a node with submissions of a webform? I'm using Drupal 7 and created a content type 'NewArticle' with the fields 'Title', 'Text' and 'Image'. Users have the permission to create a 'NewArticle', but I don't like the way of displaying the administration bar in order to let them create a 'NewArticle'.

Instead, I'd like to work with Webforms. My goal is to create a Webform with exactly the same fields as the content type 'NewArticle'. So what I want is: when users filled in the form and submit it, a new node 'NewArticle' is created with the submitted information.

How can I do this? Are there modules that make this possible? I can't find any...

Instead of using the Webforms module to create new nodes, it's better to let the users create them directly at MY-SITE/node/add/CONTENT-TYPE. Trying to hack data out of a Webform only makes things unnecessarily more complicated. Hide the toolbar for other users and give them permission to add new content. Lastly, adapt the node form to your needs with a template file and style it with CSS.


simple numeric token string 2 max 3 digits I need to generate numeric string and append it at the end of node url. Tried using some token random number options but the result is 10 digit number which is not neccessary for my purpose. Is there any other option? Node NID is not possible to use. Thank you

$length = 3; // character length
$token = substr(drupal_hmac_base64($node->nid, drupal_get_private_key() . drupal_get_hash_salt()), 0, $length);


"Page not found" on translated page I’m setting up a dual language site (English default / Chinese, Simplified) where Taxonomy translation mode is “Localize”.

I modified the Taxonomy term in Views.

I get results with preview in both default and translated language.

In page views, English is okay. However, Chinese page return “Page not found”.

I have tried Content: Has taxonomy term ID (translated) & Content: Has taxonomy term ID (with depth, translated) and a different validator "Taxonomy term (i18n)".

What did I missed? Please enlighten.

Did you set a chinese alias for your view page ?
Eg.: your view has an alias set to "my-listing" for the "EN" language.
=> Try to set a chinese alias corresponding to "my-listing" alias, but for chinese...


How to hide selected term values in Views? I have a content type with a taxonomy field called Price. Authors create content based on this content type. While doing so they select from a Price list (two options). Either they can select 'Costs Money' or 'Free'.

In Views, I want to show the value (a rendered image) if it's set to "costs money" and NOT display the field if it's set to "free".

Is there an easy way to accomplish this in Views?

I'm using Views 3 and Drupal 7.

Use the views feature "rewrite result", combined with a logic similar to the pseudo code that is below to implement the desired functionality:

if Price Term = 'Costs Money' then write the image tag related to 'Costs Money'
else write &nbsp;

Not sure if you'd actually need the else clause ...

Note: This requires the Views PHP module , as described in https://www.drupal.org/node/482752#comment-4841554 also. Attention: this module only has an alfa version as of today, but it's used in over 71K sites anyway.


Supported recurring payments I would like to activate Recurring Payments in Drupal. Is there a list of supported payment methods?

Try Commerce Recurring Framework module

Overview
Provides a rules, field and entity based approach to recurring billing
for Drupal commerce.
Features
Auto-generate new orders based on recurring configuration decoupling
payment from recurring process and leveraging the payment
responsibility directly to the payment method.

Also For more details about how you can use this  Read Recurring payments in Drupal


Are regions and features automatically created when creating a sub subtheme? I want to inherit everything from a main theme except the layout.
When I create the .info file and specify which regions and features I want are these generated automatically by drupal or do I have to specify each one in a separate .tpl file like the diagram below?

Yes, you will enherit everything unless you modify the page.tpl.php file located in /sites/all/themes/yourtheme/template folder.

The page.tpl.php file contains all block regions. Thus, you should modify this file if you want to add, remove, or move regions.

If you want to resize or theme a region, it's all css. As you will see in page.tpl.php, the regions will have a div class or id.


How to add a button :"Get my location" in page views i have created a gmap views page, and i want add a button "get my location like this :

i want give to visitor a button that can get his location in the map,
some one have an idea how to do that ?

You can use the IP Geolocation Views & Maps module for that task. It will provide you with a block that contains a button with the asked functionality. The user location will be determined via several methods:

  Finally IPGV&M provides a set of visitor location retrieval
  technologies, both IP and HTML5-based, so that you can track where
  past visits came from and where current visitors are located,
  superimposing their moving positions as markers on your maps.

Please read carefully about the requirements.


PHP Fatal error: Uncaught Error: Call to undefined function cache_get() I'm trying to get Drupal to work inside an Alpine Linux docker container but for some reason drush can't be used to manage the website. The website itselfactually works fine, drush just can't bootstrap.

Here's the pertinent information:

 /var/www/html # drush core-status
 Drupal version         :  7.56
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  vlp-dcimysql01.dhe.duke.edu
 Database port          :
 Database username      :  tmp_drupal
 Database name          :  tmp_drupal
 PHP configuration      :  /etc/php7/php.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/bin/drush
 Drush version          :  8.1.14
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /var/www/html
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

/var/www/html # drush wd-show
PHP Fatal error:  Uncaught Error: Call to undefined function cache_get() in /var/www/html/includes/module.inc:754
Stack trace:
#0 /var/www/html/includes/module.inc(954): module_implements('system_theme_in...')
#1 /var/www/html/modules/system/system.module(2511): module_invoke_all('system_theme_in...')
#2 /var/www/html/includes/theme.inc(798): _system_rebuild_theme_data()
#3 /var/www/html/includes/theme.maintenance.inc(57): list_themes()
#4 /var/www/html/includes/bootstrap.inc(2872): _drupal_maintenance_theme()
#5 /var/www/html/includes/errors.inc(179): drupal_maintenance_theme()
#6 /var/www/html/includes/bootstrap.inc(2609): _drupal_log_error(Array, true)
#7 [internal function]: _drupal_exception_handler(Object(Error))
#8 {main}
  thrown in /var/www/html/includes/module.inc on line 754
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Uncaught Error: Call to undefined function cache_get() in /var/www/html/includes/module.inc:754
Stack trace:
#0 /var/www/html/includes/module.inc(954): module_implements('system_theme_in...')
#1 /var/www/html/modules/system/system.module(2511): module_invoke_all('system_theme_in...')
#2 /var/www/html/includes/theme.inc(798): _system_rebuild_theme_data()
#3 /var/www/html/includes/theme.maintenance.inc(57): list_themes()
#4 /var/www/html/includes/bootstrap.inc(2872): _drupal_maintenance_theme()
#5 /var/www/html/includes/errors.inc(179): drupal_maintenance_theme()
#6 /var/www/html/includes/bootstrap.inc(2609): _drupal_log_error(Array, true)
#7 [internal function]: _drupal_exception_handler(Object(Error))
#8 {main}
  thrown in /var/www/html/includes/module.inc, line 754

As stated before, the platform is Alpine Linux, PHP is 7.1.9

I can add more if anything is unclear. I've checked the PHP logs but they just produce the above output. I'm open to there just being a module/extension missing, but I'm not entirely sure how to figure that out if it doesn't ever tell me "undefined function extensionFunctionX" or something like that. The above undefined function appears to be a Drupal core function.

Note that the website works, so it's communicating with the database without issue, I can also do a SHOW TABLES in MySQL and see the Drupal installer's tables were created.

In my case (moving production website to fresh server) memcached was enabled in settings.php, PHP daemon was installed and running on server, but no PHP extension was installed


Ordering/ Sorting product displays on the product category page I have created product displays which are now showing on the relevant category pages (product-category/%). The product category page is created in views which is great but I want to have full control over the order of which the products are displayed (top to bottom).

At the moment in 'Sort Criteria' of views I only have options to sort by Title, ID, Date posted and Category which is not useful. I want to sort by something like SKU or some other field of the product.

Any ideas?

How about re-making your view so it shows Commerce Products, and add
  the relationship to the product display the other way round to get
  node data? That way you should definitely have SKU available as a sort
  option from the base table (commerce_product)
  - Clive

Thanks Clive - this worked.


How to display the user edit-picture form in custom block? I am trying to customize the user edit page in Drupal7 using Panels for user-edit page. How can i display the user edit-picture form in any specific region in Drupal 7. In my panels, i added a custom text in my sidebar region as:

<?php
drupal_get_form("edit-picture") ;
?>

However, it does not show anything. I got the form id by looking at the css. Any suggestions?

The ID you pulled from the DOM isn't the form ID, unfortunately. It's just the ID of the user image picker fieldset.

Take a look at the User Picture Field module. I haven't used it, so I can't personally vouch for it. However, it does make the user picture a field, which adds a lot of flexibility. I think Panels will let you move the field to the place where you want it to appear. You should also be able to use the editablefields module to make the image editable in the display.


Best practice: needs private and public contents of same type The website need News, Image Gallery and Announcement. But all of the News, Image Gallery and Announcement has 2 types: public and private.

The private content is tend to be a "collaboration platform" for specific user role.

I've created two content types for News (news & private_news), and so on for Image Gallery and Announcement.

So the website has 6 content types. I'm using content_access to make the content type public or private.

The problem with this, I dont know the future of the website. It will fails if in the future it needs public and private forum (where forum cannot exist in 2 content types).

Choice 2: Make single content types. It needs single News content type. The field accessibility is done by using field_permissions (not yet tested) and the node visibility is same as above; using content_access

But the problem is the content types become more complex. It maybe become very heavy for the server.

Choice 3: Use different sobdomain: www.site.com for public contents, and somename.site.com for private contents (not sure what name I should choose as subdomain).

I'm not sure which one the the best if the website growing bigger (in terms of traffic and website features).

Perhaps the deciding factor is to determine if the private users need to see the private content seamlessly integrated into the public content.  If they do solutions 1 & 2 seem like they might work.  If, on the other hand, private content can or should be viewed separately from the public materials, separating into two subdomains (or even subsites) with different access rules would be much easier.


Teaser of full html pages without layout I have a block/view that shows teasers of the latest 3 articles.. This articles are full html, it contains layout (build with a WYSIWYG)..

On the homepage, I create a block that shows the latest 3 articles.. I can give it CSS-layout..

But because it's build with the WYSIWYG, there are extra html-tags (span, a, p, ...) in the teaser, which can be different every time. The problem is that it overwrites the default layout for the teasers..

I just want to keep the clean text on the frontpage block, and full-html on the detail page. How can I manage it?

Normally I should use strip_tags(); in PHP to remove html.. But how can I do it only for that specific block?

Add the body field and trim it.

Now in your web directory, go to /sites/all/themes/yourtheme/ folder and in template.php add the following code:

function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    $vars['fields']['body']->content = strip_tags($vars['fields']['body']->content);
  }

}

replace yourtheme with the actual name of your theme
replace view_name with the name of your view.
replace block_1 with the machine name of your view. If yours happens to be block_1 then leave it the same.

In Drupal, clear/flush your cache to see the changes.

Then add the other fields you want on your view, title, post date? comment link? etc... basically you create your own teaser.

PS: You can add classes to your fields, if you need to use css on them.


How to enable jEditable to perform updates? I recently installed the jEditable inline content editing module on my Drupal 7 site, as an adjunct to the DataTables module.

We need the ability to perform updates on data presented in a DataTable View. I get an error that it cannot connect to the DB.

Does anyone have experience and success in making this work?

Or is there another module/jquery method I can use that does this?

Note: I cannot perform CRUD from a views interface (hence the name views) this would be a cool option though.

Consider looking at the Editable Views module for a possible alternative. Here is a quote about it from its project page:

... lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.
Currently, the following Views fields can be edited:

all FieldAPI fields
node title


What does views UI Module do? I'm new to drupal and I have read about view UI module in many places but was not able to find what exactly it is.Can any one help me on this ?

Views UI module gives you a nice user interface to create, and edit your views.
A "view" here means what the Views module produces; it could be a slideshow, a page with a table, a block of recent comments, etc.

You can turn that module off if you have finished making all the views, and the site is ready to go on production. Your views will work no matter you have the Views UI module enabled, or not.


How to alter node title link? I want alter $node_url in node.tpl.php inside a module not in node.tpl.php, which hook should I use?

This is done in template_preprocess_node() in node.module on line 1451 (http://api.drupal.org/api/drupal/modules%21node%21node.module/function/template_preprocess_node/7).

function template_preprocess_node(&$variables) {
  ...
  $variables['node_url']  = url($uri['path'], $uri['options']);
  ...

You could change it to anything else in your own module in mymodule_preprocess_node() function like so:

function mymodule_preprocess_node(&$variables) {
  $variables['node_url'] = 'some/other/path';
}


Internal Server Error and Machine Readable Names I have installed a new local site using Drupal 8.1.10 which takes a lot of time whenever I give any command (lets say create a text field) and then sometimes it gives a 'Internal Server Error' after which the 'machine readable name' of the text field which I was creating becomes unusable.

It then gives the error 'The machine-readable name is already in use. It must be unique.' whereas the field was not created and the 'machine readable name' is not actually in use.

This has happened multiple times. How do I resolve this?

Just try this :
on .htaccess, replace Options +FollowSymLinks by Options +SymLinksIfOwnerMatch

Example from : http://www.drupal8.ovh/en/tutoriels/9/install-drupal-8-virtualmin-error-500


How to replace a preprocess function entirely? I need to replace template_preprocess_links with my own preprocess function and I can't find in the documentation how to replace a preprocess function entirely. Here is my current HOOK_theme implementation:

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path)
{
  return [
    'links' => [
      'variables' => [
        'links' => NULL,
        'raw_links' => NULL,
        'attributes' => NULL,
        'heading' => NULL
      ],
      'override preprocess functions' => TRUE
    ]
  ];
}

But even with override preprocess functions set to TRUE, the core template_preprocess_links is still called and pollute the output with rendered links.

How can I replace this preprocess function entirely?

hook_theme() is for new theme implementations, not altering the existing ones, and 'override preprocess functions' can be used just from themes.

The hook you need to implement is hook_theme_registry_alter(). The example code shows how to remove a preprocess function for a theme implementation.

function mymodule_theme_registry_alter(&$theme_registry) {
  // Kill the next/previous forum topic navigation links.
  foreach ($theme_registry['forum_topic_navigation']['preprocess functions'] as $key => $value) {
    if ($value == 'template_preprocess_forum_topic_navigation') {
      unset($theme_registry['forum_topic_navigation']['preprocess functions'][$key]);
    }
  }
}

Removing all the preprocess functions would just require a line like unset($theme_registry['forum_topic_navigation']['preprocess functions'].

The same is true for Drupal 7. (See the example code given in hook_theme_registry_alter() - Drupal 7).


Is there a way to add profile2 forms in multistep registration Is there a way to add profile2 forms into a multistep registration form?...
First of all I am a beginner I only know small tidbits on how to do multistep...
What I need is step 1 to be basic user registration information, step 2 to be personal profile2 info and a conditional set up basically asking the viewer something in a radio or click box that should process if they need a second profile. If that conditional is met then they go to step 3 and fill out a second profile2 form.

I found out about multistep here

yes definately we can create profile2 field as a multistep form for this we can use Field Group
By field group module you can include all fields in multipage group and after that create multipage group as per you need and include relevant fields in each break.