Override formatting for paragraph edit view I have a paragraph type defined as two fields, which are Person and Role.

I can customize the structure of the paragraph fine to view. However, I am stuck in editing how the form elements sit in the Edit screen.

Debugging the twig files indicates that the Theme Hook around these components is 'container' and not anything to do with 'paragraph'.

Is there either:
a. A way to specify a 'container.html.twig' file to render the paragraph's form?
b. A way to specify how the paragraph should render forms?

Is there something else I may have missed?

Most edit forms utilize your current admin theme and form render arrays with according widget subforms.

So - in theory - you have several options:

(1) Provide your own admin theme with templates for your single forms. Using a contrib admin theme as base theme would make up for an easy start.

(2) Create a custom module and implement one of the many hooks that allow to alter your forms (e.g., hook_form_FORM_ID_alter, hook_field_widget_WIDGET_TYPE_form_alter, ...).

(3) If suitable, choose your front-end theme for editing your content. Then you can implement your templates there. For this, you'd want to implement a custom theme negotiator in a custom module.

In most cases however, the above methods are overly time-consuming.

To improve usability of back-end forms for content authors, have a look into the field_group module. It allows you to structure your back-end editable forms and displays. You can add groups like detail wrappers, horizontal/vertical tabs, and/or containers with custom HTML-elements and classes.


Chart & graph as content type? is it possible with any module I want to create content type as chart and graph, any module which can render my data into chart form ?

As mentioned in the previous answer, charts is indeed a module that might be considered. In response to the comment in it about "not using views" you need to know that using views for creating charts is only one of the available use cases for the charts module, as explained in the charts community documentation. Here is the relevant quote of it:

  Various options are available to actually create charts via the charts module:

  Use the charts module directly e.g. to create a chart as part of the body of a node (using data that are hard-coded in such node).
  It can be used as a views style (views integration).
  Take advantage of the charts API to integrate it into your module, using a single function as the point of contact: charts_chart();.
  Visualize data stored in a database table (more dynamically), as explained in Chart some data stored in a database table (dynamically).

So from the above options, I believe that option "1." could perfectly address the original question. All you'd need is to enable the PHP filter (input format), and then add the relevant PHP code related to the charts render array (which is used to specify any of the desired options supported by the Charts API). As a variation of such "content type", you may also use a custom block (in which you include the same PHP code related to the charts render array).

To create charts in Drupal, there are actually dozens of modules to pick from (really!). Consider the comparison of charting modules as a possible place to start from, to find the module that best fits your needs. That comparison does include the charts module mentioned here, but quite AbitMORE charting modules ...

Possible alternatives that should solve this specific question, are the Chart module, or the Charts module. I recently created quite a lot of new Chart documentation, and Charts documentation. Though there are other alternatives in that comparison that might be a better fit for this specific case.

The license that comes with the related charting library (engine) in each of these modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. 'Possible privacy concerns' or 'Yes or no support for saving charts in PDFs' is another typical item to consider.

Recently I extended the above mentioned comparison with Maintenance Scorecards for all Native Charting Modules. These Maintenance Scorecards should help to further narrow down the available charting options if you're concerned about how well some module is maintained (or not).

Disclosure: I'm a maintainer of both module 'chart' and 'charts' (confusing names, I didn't invent those names), and the author of the comparison (+ some charting modules mentioned on my profile). I hope this does not violate the site's policy on self-promotion.


Parameter upcasting in Drupal 8 with Form Controller I have created a custom module with mymodule.routing.yml in which I am using own parameter {my_menu}. I have created a mymodule.services.yml file too in which I have used class for param conversion. Parameter conversion class is calling properly but I am not able to get the parameter in Form Controller class.

Code that I have written :

mymoudle.routing.yml :

entity.my_menu.mymodule:
  path: '/node/{my_menu}/mytab'
  defaults:
    _title: 'My Title'
    _form: '\Drupal\mymodule\Form\MyModuleformControllerForm'
  requirements:
    _permission: 'edit my page'
    _entity_access: 'my_menu.update'
  options:
    _node_operation_route: TRUE
    parameters:
      my_menu:
        type: my_menu

mymoudle.services.yml :

services:
  my_menu:
    class: Drupal\mymodule\ParamConverter\MyModuleParamConverter
    tags:
      - { name: paramconverter }

src/ParamConverter/MyModuleParamConverter.php :

/**
 * {@inheritdoc}
 */
public function convert($value, $definition, $name, array $defaults) {
  dsm($value); // Node id that exists.
  return Node::load($value);
}

/**
 * {@inheritdoc}
 */
public function applies($definition, $name, Route $route) {
  return (!empty($definition['type']) && $definition['type'] == 'my_menu');
}

src/Controller/MyModuleformControllerForm :

public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  dsm($node); // It is null here
}

Your variable needs to be called my_menu, check ControllerResolver


how to fix a block in a location? I'm using Drupal 7 with Bootstrap 3.3.5 as a theme.
I built an English version of my website and now I'm working on Arabic version which means RTL(right to left).

When I switch to Arabic, some block's location change to right or left, I'm asking if it's possible to fix the block location? If you have any suggestion about this RTL problems it will be welcome, thank you.

Your theme doesn't support RTL layout.

You need to either RTLize (flip) the CSS of your theme or replacing to a theme that does support RTL.

BT 3.0 doesn't support RTL (though there are plans to make BT 4.0 RTL supportive).

A good Drupal base theme that does support is AdavptiveTheme 8, which is also lighter in code amount.


Difference between function names from Drupal Devel The devel module in drupal allows us to print variable data using functions like:
kpr,krumo,dpm,dsm
Can anyone please explain how different is each function from the other

Maybe this can help you a bit:

dpm($var) or dsm($var) - displays the information about a variable in the form of system messages using Krumo.
dvm($var) - displays the information about a variable in the form of system messages using var_dump($var).
dpr($var, $return = false) - displays the information about a variable at the top of the page, using print_r($var, $return).
dvr($var, $return = false) - displays information about a variable at the top of the page, using var_dump($var, $return).
kpr($var, $return = false) - displays the information about a variable at the top of the page using Krumo.
dargs() - displays information about the arguments of the current function at the top of the page using Krumo.
dd($var, $label = null) - writes the information about a variable in the file drupal_debug.txt, which is located in the temporary directory (admin/settings/file-system).
ddebug_backtrace() - displays the call stack at the top of the page using Krumo.
db_queryd($query, $args = array()) - this is a debug version of db_query(), which displays it at the top of the page after the execution of $query.
dpq($query, $return = FALSE, $name = NULL) - this is an analog to the function db_queryd() only available in Drupal 7. Outputs SQL query using dpm() with substituted arguments. The first parameter takes an object DBTNG.


Get node id from a grid view I am new with D8

I have a view which lists some content about a specific content type.

I made a plugin that permit to add a custom drop button for each view rows

This button has to make some control and then redirect to a new content type or form.

This part is OK

But

I would like to know how is it possible, in the button context, I can get the node_id of the specific content :

the button in first row will return the node_id of content of row 1
the button in second row will return the node_id of content of row 2
...

so after several hours i found the good solution !
Simple solution for people not new like me on drupal. lol

In my view I added the field "Content:id" of my content_type
And checked "Exclude from display"

In my plugin .php file in the method render(ResultRow $row) i got the famous id like this :

$nid = $this->getEntity($row)->id();

that's all !!


Change the submit function for user login I'm building a site for a client that already has a website through another CMS that they do not wish to move away from despite my best efforts to convince them otherwise.

This CMS does offer an api that allows for implementation for single sign on so I'm trying to set that up.

I've gotten as far as

    function mymodule_form_alter(&$form, &$form_state, $form_id)
    {
        if ($form_id == 'user_login') {
            $form['#submit'] = ['mymodule_login'];
        }
    }

    function mymodule_login($form, &$form_state)
    {
        exit('SUCCESS');
    }

But the success message is never shown.

Oh, I tried searching to see if there was already a module that implemented this but no such luck.

Is you module named mymodule? The prefix of the hooks has to be the same as the machine readable name of your module. After checking that, try clearing the cache. After that, is should work because the code looks all right.


Publish or Un publish any comment How to give moderator a right to publish or unpublish/edit any comment , not just own comment or  comment on own content without giving "Administer comments and comment settings" Permission, by giving just a tab for publish and unpublish for appropriate role ?

Go to /admin/people/permissions and check assign the appropriate permission("Administer comments and comment settings") you'd like to the that role.
Check https://www.drupal.org/node/777696


Importing node_revisions records from version 5 to version 6 Probably a dumb question, but could I simply export an SQL file from the database of a Drupal 5 site and import it into a Drupal 6 database in the same table provided I used the same CCK fields for both? I've tried to migrate content in so many different ways and pretty much everything has failed so far... importing csv through the feeds module was my greatest hope and was made to look so easy but I keep getting an HTTP error.

Also is node_revisions the table that contains all of the stories? I tried exporting nodes, but it didn't seem to contain the body field.

Instead of trying some convoluted way of exporting and then re-importing the data and maintaining all meta-data - have you tried simply upgrading the site to Drupal 6?

This has been heavily documented on drupal.org

When you do a major drupal upgrade, so long as there is a drupal 6 module for your functionality, there will be update hooks that alter the database to convert it to the new schema.

This includes CCK, revisions etc


Profile 2, user relation access? A hard one! The site contains 2 user types besides admin, lets call the 2 user types "Private" and "Corporate".

Private users have a "profile 2" type, where alot of different fields are filled.

In a view or likewise, "Corporate" users need the ability to search for users, and when they go to a users profile, ONLY a few fields should be visible - rest hidden.

Then when (Corporate user) viewing the (Private users) profile, they need a "button" or likewhise where they can ask for permission to view full profile.

Now the private user should recieve a mail that states a "Corporate user xxx" want to see their full profile. ONLY when the "Private" have accepted this, all fields should be visible, BUT ONLY to this ONE specific user of the "Corporate" role - not all other users with the "Corporate" role.

What modules can make this node/user access work?

Here is a zero code solution.

Flag + Rules + Rules Block Visibility
 + Views

1 flag for "request"

1 flag for "allow"

When "request" flag is flagged >> send e-mail with link to flagging user profile.

Then other person opens link and sees their profile and clicks the "allow" flag.

If user is listed in the Allowed flag list, then show View Block with the all the fields, if not, then show View block with limited fields.

Here is an indepth example to using Rules Block Visibility: How to stop a Views block from displaying to admins, such as user/1?


What is the best way to store a guid? I found that the best way to store a guid is as a char(36) data type for MySQL.
What is the equivalent to char(36) in drupal 7?

In terms of core function I don't think there's a lot of choice you can have.  You'd have to use the "text" field type and limit to 36 chars.


Content type slug in route, how? I have a content type "Company", each company will have a login page that show the logo of the company and a login form via Restful.

I have created a module that define a route:

company_md.login:
  path: '/{company_slug}/login'
  defaults:
    _controller: '\Drupal\company_md\Controller\DefaultController::login'
    _title: 'Company XX Login'

When I go to that URL it give me Not Found 404, whats wrong in my routing?

EDIT 1

This how the path look:

http://companies.local/node-13-company/login4

EDIT 2

My routing file:

testd8.name:
  path: '/node/{node1}/login'
  defaults:
    _controller: '\Drupal\testd8\Controller\DefaultController::login'
  requirements:
    _access: 'TRUE'
  options:
    parameters:
      node1:
        type: entity:node

Do you have an entity type or a content type? If you create one in the UI, it's a content Type. Then it really is a node, so what you want to use is {node}. Then upcasting will work (assuming you have NodeInterface $node in your controller).

That said, access denied is, as Ivan Jaros said, the missing access definitions. The default access definition is that that access is denied. access: 'TRUE' will give anyone access.

What you likely want to use is _entity_access: node:view then the standard node access system is invoked and the user has access if he can view that node.


Redirect user based on role and node content I want to redirect a user when they login based on what role they have and whether they have created a node of a type.

So if the user has administrator role, direct user to admin url
else if
the user has role list_user, check if user has content of type new listing, if they don't, direct them to create node listing if they do have created node of type listing, direct them to profile.

I have this set up in separate rules but I'm sure it will work better and faster by just having one php block of code in the template.php

My only problem is, I don't know php and everything I've tried doesn't work very well or not at all.

Any help would be appreciated.

Use Rules module to redirect based on user roles.

After Installing Rules module, Go to Admin -> Configuration -> Rules (admin/config/workflow/rules/)
Add new rule
Enter rule name & select User has logged in from React on Event
Add new condition and set User has Role Select the required role and Save
In Action add new action Set it Page Redirect & enter the redirection URL


PHP print in Basic page I am facing what I think it is a strange behavior...

I have a Basic Page with PHP code in it. In this PHP code, I have some "Print".

Now, no matter the page I am displaying on the website, I got those prints in the bottom of my page...

Is that normal? How can I change that?

Regards!

This is working as intended.

  I have a Basic Page with PHP code in it. In this PHP code, I have some "Print".

You should not have any PHP (not "print" or anything else) as part of the content of a node.  Drupal is designed to treat PHP in nodes as text, and will just output it verbatim. Anything else would create a huge security hole in your site.

Just delete those "print" statements, and they will no longer appear.


Problem with field storage for custom content type modules I have multiple modules for custom content types (like "node_type_food" and "node_type_wine"), based on "node_type_example" in the drupal examples module.

I can install a content type like "node_type_food" without any problems but  installing a second content type like "node_type_wine" with a common field (food & wine both have a field "field_text") results in this error:

  Unable to install Content type wine, field.storage.node.field_text
  already exists in active configuration.

Without the field.storage.node.field_text.yml in config/install I can't install a content type when no other content type provides the field storage..

  Unable to install Node type wine, field.field.node.wine.field_text has
  unmet dependencies.

Edit: Problem also descibed in comment on Install a module that creates a content type with fileds via YAML

The Drupal's config management system which are you using to install configuration isn't really built for this. There are several ways to go about this. The main issue is that the config management system automatically create dependencies and such for you, which is a bit troublesome to manage.

Drupal doesn't have a concept of a shared field, it simple has a field store and field instance, but this isn't owned by a module.

So for solutions, there are some ways to go about this.

Let one module own the field storages you want to want to share and let modules that share fields depend on the module. Note the field can be deleted eventhough it's in a modules install folder, as it's just configuration, unless you lock it. A variation of this would be to combine the modules, into a single module, so all config is install at the same time.
Don't use shared fields - if the modules are independent, it makes sense that they shouldn't share configuration.
Use code to install fields. This is similar to how you define fields for entities, only you need to use FieldConfig and FieldStorageConfig. Drupal have many test cases that does this, which you can use as a guide. Some example code looks like this:

$this->fieldStorage = FieldStorageConfig::loadByName('entity_test', $field_name);
if (!$this->fieldStorage) {
  $this->fieldStorage = FieldStorageConfig::create(array(
    'field_name' => $field_name,
    'entity_type' => 'entity_test',
    'type' => 'link',
  ));
  $this->fieldStorage->save();
}

$this->field = FieldConfig::create([
  'field_storage' => $this->fieldStorage,
  'bundle' => 'entity_test',
  'settings' => array(
    'title' => DRUPAL_DISABLED,
    'link_type' => LinkItemInterface::LINK_GENERIC,
  ),
]);
$this->field->save();


Home page only page accessible, no login with clean urls I'm trying to copy a live site to my windows development machine for some module testing and updates. I have a copy of the complete live site's codebase (entire drupal root from live server) and the the sql dump file for the live site.

I'm using Acquia's Dev Desktop, and I use the import local site option, point the installer to the correct files and sql dump. The issue is that the installation seems to fail, in that navigating to the site triggers the installation script, and my database name and settings are imported but the database itself is empty. I then imported the correct database manually and ran the update.php script, but then only my home page shows up. Any page that isn't the home page gives me a 404 error, and I can't use clean urls to login, ?q=user/login also gets me a 404.

I've checked the .htaccess file and it exists.

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

I don't think it would have to with my Apache settings because, that should all be taken care of by Acquia installer.

Where on the computer should the codebase folder be placed?

Is there anything special to how I should be copying the files?

If the Acquia Dev Desktop configured Apache correctly, then you're most likely missing your .htaccess file in the root of your Drupal install.

I know sometimes on Windows machines .htaccess is hidden within FTP clients, and you need to change a setting so that  you can see the file in directory listings.

The content of your .htaccess file you posted is from the Drupal files directory, which is usually located within /sites/default/files

Double check that you .htaccess exists in the route, and that it has the correct contents. I'd recommend grabbing an original copy from Drupal core.


Is the video processing of the ffmpeg transcoder done locally on my server? When configuring the Video module, I'm posed to choose either ffmpeg or Zencoder transcoder.

While it's clear that Zencoder leverages video transcoding cloud services by Zencoder.com, I wonder if the ffmpeg option here means video processing is done locally on my server?

In other words, does ffmpeg option use the computing power of my own server and therefore it's completely free?

FFmpeg is licensed under GNU Lesser General Public License (LGPL) version 2.1 or GNU General Public License (GPL) version 2, depending on compiling options. Both are free and open source.

As far as I see in the code (just glanced over it, mind), both Video Presets and FFmpeg Converter uses locally installed converter. Will it be free? Probably not. Looking on FFmpeg Converter page:

  Note: This module is not for beginners, since FFmpeg requires rather complicated server configuration.

Sysadmin's time usually isn't free, CPU power also is not. But you should be free from licence fees all right.


Hidding view tab on node/%/view I've successfully managed to hide "View" tab on node page with this code:

/*
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data){

    foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == "node/%/view"){
            unset($data['tabs'][0]['output'][$key]);
        }
    }
}

but when I enter the frontpage this error is displayed:

  Notice: Undefined offset: 0 in custom_alter_menu_local_tasks_alter()...
  Warning: Invalid argument supplied for foreach() in custom_alter_menu_local_tasks_alter()...

This line that causes the error is the following.

foreach ($data['tabs'][0]['output'] as $key => $value) {

I don't know what is wrong with the code. On frontpage there are no tabs and I don't have custom coding there.

I'm using Drupal 7.

The way to hide the node/%/view tab is to implement hook_menu_alter(), and change the menu defined from the Node module, which uses the following definitions.

  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),

    // The page callback also invokes drupal_set_title() in case
    // the menu router's title is overridden by a menu link.
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
  $items['node/%node/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['node/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'node_page_edit',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'node.pages.inc',
  );

In particular, you need to change the menu type for node/%node/view from MENU_DEFAULT_LOCAL_TASK to MENU_CALLBACK, and change the type for node/%node/edit from MENU_LOCAL_TASK to MENU_DEFAULT_LOCAL_TASK.

MENU_CALLBACK keeps the menu item still accessible for those users who have the permission to see it, but the menu item would not be visible as tab or link.

As for using hook_local_task_alter(), I don't see Drupal core modules that alter the tabs added from other modules, but looking at blog_local_task_alter(), I notice the following code.

  if ($root_path == 'blog') {
    $item = menu_get_item('node/add/blog');
    if ($item['access']) {
      $item['title'] = t('Create new blog entry');
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }
  // Provide a helper action link to the author on the 'blog/%' page.
  elseif ($root_path == 'blog/%' && $router_item['page_arguments'][0]->uid == $user->uid) {
    $data['actions']['output']['blog'] = array(
      '#theme' => 'menu_local_action',
    );
    if (user_access('create blog content')) {
      $data['actions']['output']['blog']['#link']['title'] = t('Post new blog entry.');
      $data['actions']['output']['blog']['#link']['href'] = 'node/add/blog';
    }
    else {
      $data['actions']['output']['blog']['#link']['title'] = t('You are not allowed to post a new blog entry.');
    }
  }

In your case, you should check that $root_path is equal to node/%; in that way you would avoid to do something when the page being shown is the front page. (If node/% doesn't work, then node/%node should.)

I still think that hook_local_tasks_alter() should not be used in this case, as it seems to me that hook_local_tasks_alter() is thought to be used when altering the tabs depends from the page being viewed, as blog_local_task_alter() shows.


One of my drop down menus, the "Create Content" option under the parent "Content" tab has dissapeared. How can I recover it? (I'm using Drupal 7) One of my drop down menus, the "Create Content" option under the parent "Content Management" tab has dissapeared. The missing "Create Content" would normally be under "Content Management."

How can I recover it? (I'm using Drupal 7).

Help much appreciated. Thanks.

It looks like you're using admin menu, right? A blog post about rebuilding the drupal admin menu says you can:

Delete you current links via SQL DELETE FROM menu_links WHERE menu_name='management'.
Clear all caches at Administration > Configuration > Development (or just: http://example.com/admin/config/development/performance if your menu is ruined at this point). Drush users can of curse use drush cc all or even drush cc menu

Disclaimer, I didn't try it myself. Hope this helps.


How do I use the Cufón module to change the title of a view? I bought a new theme and I am not getting much support from the place I bought it from. My theme has nice fancy titles in blocks, which are implemented using the Cufón module to change the text. I was wondering if it was possible to do the same with the title of my views.

I have tried overriding the views-view-table-tpl and added <h2 class="title cufon"> around the title, but it didn't have any effect.

How can I achieve this?

Edit the page.tpl.php template, and add the cufon class to the page title (<h1>). Alternatively add a h1.title rule to the Cufón module.

If you dont't use the Cufón module, add this to your template.php.

drupal_add_js('Cufon.replace('h1.title');', 'inline');


hook into third party API after checkout I wondering where to get started on this, I have ubercart core 6.x-2.10 installed and configured with authorize.net.  after a user purchases a "product" I want them to be registered on a third party webinar site. Where in the code would I start are there any extra modules I should use?

You should probably be looking to use the hook_uc_checkout_complete() hook.

From the docs, it takes two parameters, $order and $account - I'm guessing $account will be the one you'll need to create the account on the third party web service as it's the object that contains the customer/user information.

The registration part of your question depends completely on which third-party web service you are talking about, and will probably fall outside the scope of Drupal Answers unless there is either an existing integration module, or you are looking to write one and need help on the Drupal side of things (i.e. this is not the place for general API usage questions).


Content not unpublished I am trying to unpublish some content by going to admin/content and then checking the chechbox for those content and then in update options i do a Unpublish selected content but then i get an error: The website encountered an unexpected error...I check the logs i get the error:

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value:
 '' for column 'field_time_to_finish_countdown_timer' at row 1:
 INSERT INTO {field_data_field_time_to_finish} (entity_type, entity_id,
 revision_id, bundle, delta, language, field_time_to_finish_countdown_timer)
 VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2,
 :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5,
 :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => node
 [:db_insert_placeholder_1] => 135 [:db_insert_placeholder_2] => 174
 [:db_insert_placeholder_3] => challenge [:db_insert_placeholder_4] => 0
 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => ) in
 field_sql_storage_field_storage_write()
 (line 448 of
 /home/qa/ypwb/public_html/modules/field/modules/field_sql_storage/field_sql_storage.module).

What is this and how can i rectify that?

It seems you added the field field_time_to_finish_countdown_timer to your content type challenge after you created some content for this type.

The previously created content do not have any value for this field, causing this error. You may define a default value for this field, such as 0 to get rid of this error.


How to create Media entity and attach to user field I'm trying to import user profile pictures from Drupal 7 to Drupal 8. So far I've managed to upload the picture from the url and save it to the file system, create Media entity and use the user id as author. However, the picture doesn't show to the user profile (Manage Form Display), neither to the Edit Media Content Type page.
Here is the code I have so far:
$values = array(
      'name' => $user["name"],
      'pass' => [
         'value' => $user["pass"],
         'pre_hashed' => TRUE,
      ],
      'status' => $user["status"],
      'mail' => $user["mail"],
      'field_first_name' => $user["field_first_name"],
      'field_last_name' => $user["field_last_name"],
);

$userStorage = \Drupal::entityTypeManager()->getStorage('user');
$userEntity = $userStorage->create($values);

    $replaced = str_replace("\\", "", $user["picture"]);
    $imageData = file_get_contents($replaced);
    $fileName = basename($replaced);
    $file = file_save_data(
        $imageData,
        "public://". $fileName,
        FileSystemInterface::EXISTS_RENAME
    );

    $media = Media::create([
        'bundle' => 'image',
        'uid' => $userEntity->id(),
        'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
        'field_media_file' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
        ],
        'thumbnail' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
        ],
    ]);

    $media->setName($fileName)->setPublished(TRUE)->save();

    $userEntity->field_user_picture->appendItem($media);

Is the something missing in the code?
UPDATE
I noticed (as also pointed out in the comments) $userEntity->save(); is missing after $userEntity->field_user_picture->appendItem($media);.
However, after I added that line, I get the following error:
Error: Call to undefined method Drupal\media\Entity\Media::getFileUri() in Drupal\image\Plugin\Field\FieldType\ImageItem->preSave() (line 321 of /var/www/html/web/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php) #0 /var/www/html/web/core/lib/Drupal/Core/Field/FieldItemList.php(233): Drupal\image\Plugin\Field\FieldType\ImageItem->preSave()

Is it related to file_save_data() function?

I've found the solution.
I don't need to create a Media entity and append it to the User entity, since the profile picture field type is Image, so I just need to add the file->id() to the specific field.
Here is the code:
$replaced = str_replace("\\", "", $user["picture"]);
$imageData = file_get_contents($replaced);
$fileName = basename($replaced);
$file = file_save_data(
      $imageData,
      "public://". $fileName,
      FileSystemInterface::EXISTS_RENAME
);

$values = array(
      'name' => $user["name"],
      'pass' => [
         'value' => $user["pass"],
         'pre_hashed' => TRUE,
      ],
      'field_user_picture' => array('target_id' =>$file->id()),
      'status' => $user["status"],
      'mail' => $user["mail"],
      'field_first_name' => $user["field_first_name"],
      'field_last_name' => $user["field_last_name"],
);

$userStorage = \Drupal::entityTypeManager()->getStorage('user');
$userEntity = $userStorage->create($values);

Then, if required, I can create the Media entity as following:
$media = Media::create([
          'bundle' => 'image',
          'uid' => $userEntity->id(),
          'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
          'field_media_image' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
          ],
          'thumbnail' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
          ],
]);

$media->setName($fileName)->setPublished(TRUE)->save();


No menu link is working after the website is deployed on hosting server I developed a website in the drupal and I have been accessing it in the development environment using the url like this "http://localhost/foldername"...

Now I have deployed the website (the folder "foldername" and database) to my Linux based hosting server.

I have to access it for testing using a URL like this "http://HostingServerIpAddress/~HostingServerUserName/foldername".

To my surprise, no menu link is working over there :( the paths are correct. The menu links which were opening in my local environment, are giving 404 error when opened using hosting urls... :(

Please guide me at your earliest.

When I move a site to the production environment and can only access it using an URL as you describe, I have to disable Drupal's 'Clean URLs' functionality (admin/config/search/clean-urls) in order for menu links to work properly (and probably clear the caches afterwards).

Edit:

In the documentation on configuring clean URLs, I found that changing the RewriteBase setting in the .htaccess file is the solution for me to have clean URLs once again.

So, in your case it probably should be: RewriteBase /~HostingServerUserName/foldername


Add microdata to breadcrumbs - Some trouble with hooks I'm trying to add microdata to the breadcrumbs. I found on the web this fix which I tried to include to my own SEO module like this:

function mymod_page_alter(&$variables) {
    if (!isset($variables['breadcrumb'])) {
        $variables['breadcrumb'] = theme('my_microdata', array('breadcrumb' => drupal_get_breadcrumb()));
    }
}
function mymod_theme($existing, $type, $theme, $path) {
  return array(
    'my_microdata' => array(
     'variables' => array('breadcrumb' =>array()),
    ),
  );
}
function mymod_menu_breadcrumb_alter(&$active_trail, $item){
  foreach($active_trail as $id=>$active_trail_item){
    $active_trail[$id]['localized_options']['attributes']['itemprop'][]="url";
  }
}
function theme_my_microdata($variables){
 $breadcrumb=$variables['breadcrumb'];
print_r(debug_backtrace());
 $output="*+*+*+*+*";
  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '
' . t('You are here') . '
';
    $output .= '
';
    $separator="";
    foreach($breadcrumb as $breadcrumb_item){
      $output.=''.$separator.$breadcrumb_item."";
      $separator="»";
    }
    $output .='
';
  }

    return $output."xXxXxXx";
}

So far I checked that all this code is executed. But this theming is not applied on my page. Why does my code not work? Could this been related with the module breadcrumb? I know that this output will be garbage but I cannot see the result.

If I guess right than is the output created by theme.inc line 1682ff theme_breadcrumb(...)instead of my code. How can I change that?

I just found the theme_breadcrumbs there is shown in their solution this line:

function YOURTHEME_breadcrumb($variables) {

Well can YOURTHEME my module name or have I to build a theme?

Your implementation of hook_page_alter() doesn't work because the parameter passed to the hook ($page) doesn't contain $page['breadcrumb'].

I used the following code to verify the content of the parameter passed as argument.

$path = 'node/14';

if ($router_item = menu_get_item($path)) {
  if ($router_item['access']) {
    if ($router_item['include_file']) {
      require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
    }
    $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
  }
}

$main_content_display = &drupal_static('system_main_content_added', FALSE);

if (is_string($page_callback_result) || (is_array($page_callback_result) && (!isset($page_callback_result['#type']) || ($page_callback_result['#type'] != 'page')))) {
  drupal_set_page_content($page_callback_result);
  $page_callback_result = element_info('page');
}

foreach (module_implements('page_build') as $module) {
  $function = $module . '_page_build';
  $function($page_callback_result);
}

drupal_alter('page', $page_callback_result);

if (!$main_content_display) {
  $page_callback_result['content']['system_main'] = drupal_set_page_content();
}

dsm($page_callback_result);

"node/14" is the path for an "Article" node I have on my test site.
The code has been created looking at the code of different Drupal functions: drupal_deliver_html_page(), drupal_deliver_page(), and menu_execute_active_handler(). It requires the Devel module, as it uses one of its functions.

This is the output given by dsm().

You can override the theme function used for the breadcrumb, implementing hook_theme_registry_alter().

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['breadcrumb'])) {
    $theme_registry['breadcrumb']['function'] = 'theme_mymodule_breadcrumb';
  }
}

theme_mymodule_breadcrumb() is the function that replaces theme_breadcrumb(), and it gets the same parameters.

  $variables: An associative array containing:

  breadcrumb: An array containing the breadcrumb links.

The theme function should be overridden if you want to alter its output. If you want to alter the value of the variables passed to theme_breadcrumb(), with Drupal 7 you can implement a preprocess function.

function mymodule_preprocess_breadcrumb(&$variables) {
  // Your code.
}


A View listing Multiple Locations and each Location having it's Own Map I am using Google Store Locator for to list a locations, I have a use case where some of the locations have special events. I want a small map next to each listing.

I've added some items to the Store Location content type to select if that location is having an event with some other fields relevant to the event.

With that, I've created a view that shows everything I need, except for a small map of the location next to the event listing. You can see what I'm going for here:

I'm stuck on how to add the map. I know I have the location information I need in the content type, but there doesn't seem to be any "map" format I can use in the view. I'm assuming I'll need another module or something custom.Looking at OpenLayers, it looks like it adds multiple markers to one map like a lot of the other solutions, anyone know if it can do what I'm asking?

The map doesn't need to be interactive, I'd take a static image that linked out the the location in Google maps.

I was able to use the Address Field Static Map module to get this taken care of.

Since I was already capturing the address in the content type, after installing the Address Field Static Map Module, I could add another 'location' field to my View and select the 'Address Field Static Map' field formatter and customize as needed from there. The module even provided an option for linking out to the location in Google Maps.

To use this, the Address Field Module is a dependency.

This gave me the exact thing I needed.


How programatically choose between multiple shipping methods commerce_shipping? I'm using Commerce Shipping Postal Code Weight to configure weight based shipping very happily. However, I have cases where I need to use flat rate shipping for certain items. The issue is that I don't know how to resolve the conflict between the shipping services. The particular case I have is that the weight-based shipping charge is less, and I don't want to show that to the customers.

So, how do I set up the conditions, where different shipping services are called?

So, this doesn't answer the question as posted but all I had to do was set my series of conditions for the Postal Code Weight method. My scenario had to Flat Rate Shipping methods based on specific products in the cart. What I did was configure the Rule for Commerce Shipping Postal Code Weight with two conditions, 1) that it didn't contain one of the products, and  2) AN and OR condition that it didn't contain a product. I also had to specify the conditions for the two Flat Rate Methods similarly, one had to have an exclusion targeting the first product condition.


Restricting the term reference field from creating a new vocabulary term I have a term reference field in a form and it is an auto-complete term widget, it has a vocabulary that supplies the values to it. My intention is to allow users to input only the terms which are defined with in the vocabulary and it shouldn't accept entries other than the vocabulary terms. But, the field is allowing other entries from the user.

For example, consider the term reference field is associated with a vocabulary. Now,if an user enters the values(other than the vocabulary terms) within that field and submits the form. It accepts the values and inturn creating a new vocabulary term with the given values. Here I want to restrict the automatic creation of terms. If the value is not defined in the vocabulary terms, it shouldn't accept the form.

I want to restrict user to enter the values which are defined. If a user enters the value which is not defined in the vocabulary, it should give an error message.

Here, my problem is the vocabulary has already been assigned with some data and I couldn't delete the vocabulary anymore.

Any alternatives to restrict the term references??

Is there a specific reason why you want users to type in the term? You should be able to change the widget type to something else (select list or multiselect). This has also been discussed at length as an issue against the Taxonomy module (Autocomplete term widget: disable creation of new terms).


Drupal commerce order notification to field in a line item type I have a Drupal 7 install using Drupal Commerce to handle donations. I created a line item type called donations, with fields such as donation amount, anonymous donation, etc.

One field of the donation line item type is called honoree email, which is an optional email field that when filled out is suppose to sends the donation order to the user who created it and the honoree.

In order to send the email to the honoree, I wanted to add a new action to the "Send an order notification e-mail" rule and use data selection to highlight the honoree email field in the "To" value. However, I am unable to find the honoree field. My data selector looks like this:

commerce-order:commerce-line-items:...

and I'm presented with an array 0-3;
commerce-order:commerce-line-items:0:
commerce-order:commerce-line-items:1:
commerce-order:commerce-line-items:2:
commerce-order:commerce-line-items:3:

I'm not sure what the differences are, and the values under each of those keys do not include the custom fields the I added to the donation line item.

How do I access the honoree email field?

What you've encountered here is how Rules deals with multi-value fields. The commerce-line-items field is a multi-value line item reference field using "delta" values represented by those 0, 1, 2, 3, etc. numbers. Without knowing the full details of your situation, the best I can recommend is to add a loop over that commerce-line-items field, passing each line item to a Rules component designed to e-mail the honoree.

If you aren't familiar with Rules components, that's certainly more than we can get into here. Your best bet would be to find the Rules Mastery course on YouTube and get your learnin' on.

Once you have the idea, what you'll need is a Rule component that accepts a Commerce Line Item as a parameter. It should have at least these two conditions:

Entity has field - does the line item have your honoree e-mail field?
Data value is empty (negated) - does the honoree e-mail field have a value?

If so, your actions section can send the necessary e-mail using the value of that field as the e-mail recipient.


Go to Checkout Complete without checkout payment I created a field field_cel_ck_scholar. It's a boolean.
I created this field in a customer profile type. My customer profile type is added in a pane in my checkout.

When this field is equal TRUE, I want by pass the checkout/%/payment's page and to redirect the checkout/%/complete's page.

It's possible ?

I try to use Rules like so:

{ "rules_by_pass" : {
"LABEL" : "by pass",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_checkout", "commerce_rules_extra" ],
"ON" : { "commerce_rules_extra_process_checkout_page" : [] },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "site:current-cart-order" ],
      "field" : "field_cel_ck_scholar"
    }
  }
],
"DO" : [
  { "commerce_checkout_complete" : { "commerce_order" : [ "site:current-cart-order" ] } }
]
}
}

It doesn't work, why?

Seems like you're trying to create a Rules condition like so:

  if field field_cel_ck_scholar=TRUE

whereas you have such field added in your 'customer profile type'.

Looking at the rule you create so far, your Rules condition seems incomplete:

you already do have the entity_has_field, that's OK, and actually one (out of 2) ways to be able to create such condition like "if field field_cel_ck_scholar=TRUE".
your Rules condition seems to be missing the actual Data comparison condition, in which you actually specify that "if field field_cel_ck_scholar=TRUE".

So try adding such Data Comparison condition, and check if that solves your issue. Not sure if it will be the only reason why "It doesn't work", but for sure a reason why it cannot work.

PS: refer to my answer to the question about How to specify a Rules condition related to select list values? for a similar (though not duplicate) question, which includes some more details (and background info) about such entity_has_field.


Create custom token Drupal 7 Creation of custom tokens / placeholder for Drupal 7. I searched many forums to get any help regarding the creation of custom tokens but I failed in getting a proper solution that's why I decided to post this topic to help drupal users.

hook_token_info
hook_tokens($type, $tokens, array $data = array(), array $options =
array())
token_replace($text, array $data = array(), array $options = array())

For creating custom token we will use three token api function.

<?php
/**
* Implements hook_token_info(). This hook will register tow token lname and fname.
*/
function myhook_token_info() {
  $info['tokens']['custom']['fname'] = array(
    'name' => t('First name'),
    'description' => t('First name re placer for fname '),
  );
  $info['tokens']['custom']['lname'] = array(
    'name' => t('Last name'),
    'description' => t('Last name re placer for lname '),
  );
  return $info;
}

/**
* Implements hook_tokens(). This hook will operate the token and replace it with it's value.
*/
function myhook_tokens($type, $tokens, array $data = array(), array $options = array()) {
    $replacements = array();
    $sanitize = !empty($options['sanitize']);
    if ($type == 'custom') {
        foreach ($tokens as $name => $original) {
              if (array_key_exists($name, $data)) {
                  $replacements[$original] = $data[$name];
              }
        }
    }
    return $replacements;
}

/**
* Here we will use the token_replace() function to get the actual content after replacement.
*/
function myhook_myfunction() {
    $custom = array();
    $custom['fname'] = 'Rajat';
    $custom['lname'] = 'Gusain';
    $data = $custom;
    $temp = "Full name : [custom:fname] [custom:lname]";
    $temp = token_replace($temp, $data);
// After token replacement $temp variable will contain " Full name : Rajat Gusain"
}
?>

What I came up with, fully documented.

/**
* @file
* Provides special token to use with pathauto.
*
* @see http://drupal.org/node/1308488
*/

/**
* Provide information about our custom placeholder/token.
*
* @see http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_token_info/7
* @see http://api.lullabot.com/token_example_token_info/7
* @return array
*   An associative array of available tokens and token types.
*/
function MODULE_NAME_token_info() {
  $info['tokens']['node']['pathauto'] = array(
    'name' => t('Pathauto'),
    'description' => t('Title ready for use with pathauto.'),
  );
  return $info;
}

/**
* Provide replacement values for placeholder tokens.
*
* @see http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_tokens/7
* @see http://api.lullabot.com/token_example_tokens/7
* @param string $type
*   The machine-readable name of the type (group) of token being replaced, such
*   as 'node', 'user', or another type defined by a hook_token_info()
*   implementation.
* @param array $tokens
*   An array of tokens to be replaced. The keys are the machine-readable token
*   names, and the values are the raw [type:token] strings that appeared in the
*   original text.
* @param array $data (optional)
*   An associative array of data objects to be used when generating replacement
*   values, as supplied in the $data parameter to token_replace().
* @param array $options (optional)
*   An associative array of options for token replacement; see token_replace()
*   for possible values.
* @return array
*   An associative array of replacement values, keyed by the raw [type:token]
*   strings from the original text.
*/
function MODULE_NAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'pathauto':
          $replacements[$original] = str_replace('&amp;', '&'), 'and',
            $sanitize ? filter_xss($node->title) : $node->title);
          break;
      }
    }
  }

  return $replacements;
}
?>


What's the workflow behind [user:display-name] token? I have seen in an email template, a token named [user:display-name]. Further noted that this token is not global, its value will only get rendered in email templates (correct me if I'm wrong).

How these specific tokens specially designed for only email tokens have been created?

In which file its logic is been written, I'm so curious, as the current user does not store any value of email receiver to whom email has to be sent. Then from where it picks the value of display name when current user is sending mail.

As Clive said, the tokens are generated from hook_token_info() and hook_tokens(). For the User entity, those hooks are implemented from the User module. Token values aren't available just for email templates, but for every function/method that uses the token service. For example, in a controller, I could use code similar to the following one.

$bubbleable_metadata = new BubbleableMetadata();
$build['#markup'] = $this->tokenService->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata);
$bubbleable_metadata->applyTo($build);

As for getting the display name of a user account, that is easy: When user tokens are generated, user_tokens() gets a user object; calling User::getDisplayName() on that user object returns its display name.
See the code used from user_tokens(); in particular, see the following code. (Comments are mine.)

// Retrieves the user object passed to the hook.
$account = $data['user'];

// Generates the value for the display name token.
$replacements[$original] = $account
  ->getDisplayName();
if ($account->isAnonymous()) {
  $bubbleable_metadata->addCacheableDependency(\Drupal::config('user.settings'));
}

It is true there are user tokens available only for email templates, but that are generated from a callback used when replacing tokens in email templates. See user_mail() and user_mail_tokens().

  // user_mail()
  $token_service = \Drupal::token();
  $language_manager = \Drupal::languageManager();
  $langcode = $message['langcode'];
  $variables = ['user' => $params['account']];
  $language = $language_manager->getLanguage($params['account']
    ->getPreferredLangcode());
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);
  $mail_config = \Drupal::config('user.mail');
  $token_options = [
    'langcode' => $langcode,
    'callback' => 'user_mail_tokens',
    'clear' => TRUE,
  ];
  $message['subject'] .= PlainTextOutput::renderFromHtml($token_service
->replace($mail_config->get($key . '.subject'), $variables, $token_options));
  $message['body'][] = $token_service
    ->replace($mail_config->get($key . '.body'), $variables, $token_options);

function user_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
  }
}

user_mail() says to Token::replace() that user_mail_tokens() must be called after all the tokens are generated, and user_mail_tokens() replaces [user:one-time-login-url] and [user:one-time-cancel-url] (not replaced from Token::replace()) with the right values.

Similar code can be used from any module to generate tokens that must be  available only in specific context.


How do you display fields created via the File Entity settings configuration? I'm using the File Entity module, and it lets me modify the configuration settings, adding a few fields to a file type, but I can't seem to figure out how to get the custom fields I created to show up in the add content screen. Only the Alt text and Title values show up. What am I missing?

I was also looking for that functionality, and found this module does exactly that: File Entity Inline

  This module aims to provide the ability to edit File entities inline,
  as part of another form (such as nodes). This should enable the
  ability for reusable and site-wide editing of file properties, such as
  description, alt text, captions, bylines, etc.


Display custom field content in node.tpl i've a custom filefield in a custom content type and i use to display it in a node.tpl .But here my filefield has no limit number and under D6 i use this code :

    foreach($node->field_objectif_bts as $file) {
  if ($file['view']) {
      $header = array('data' => 'Les objectifs des formations BTS');
      $rows[] = array($file['view']);
      $attributes = array('id'=> 'objectif-bts','sticky' => FALSE);
    }
}

$output = theme('table', $header,$rows, $attributes);
print $output;

In Drupal 7 it doesn't work, so I'm looking for modifications to do on this code or new code for Drupal 7 theming.

Actually, I tried the following.

foreach($node->field_objectif_bts as $file) {
  if ($file['und']['value']) {
      $header = array('data' => 'Les objectifs des formations BTS');
      $rows = array($file['und'][0]['value']);
      $attributes = array('id'=> 'objectif-bts','sticky' => FALSE);
    }
}

$output = theme('table', array('header' => $header, 'rows'=> $rows), $attributes);
print $output;

I also tried this code, but I get an error.

$w = entity_metadata_wrapper('node', $node);
foreach ($w->field_objectif_bts->getIterator() as $file_w) {
  // $file_w->file returns the wrapper of the File entity. You can
  // then address it's values as:
  $name = $file_w->file->name->value();
  $mime = $file_w->file->mime->value();
  $custom_field = $file_w->file->field_objectif_bts->value();
  // etc. You can see all available fields by inspecting the
  // return value of $file_w->file->getPropertyInfo()
  if ($custom_field) {
      $header = array('data' => 'Les objectifs des formations BTS');
      $rows = array($custom_field);
      $attributes = array('id'=> 'objectif-bts','sticky' => FALSE);
    }
    $output = theme('table', array('header' => $header, 'rows'=> $rows), $attributes);
print $output;
}

The error is the following:

  EntityMetadataWrapperException: Unknown data property field_objectif_bts. in EntityStructureWrapper->getPropertyInfo() (line 339 of /var/www/drupal7/sites/all/modules/entity/includes/entity.wrapper.inc).

There are two parts in your problem: one is getting the values, and the second is themeing them.

As far as getting the values is concerned, if you don't mind using the Entity and File Entity modules, a simpler way to access field content is to use entity metadata wrappers. This way you don't need to worry about deltas and languages.

You can write code as follows:

$w = entity_metadata_wrapper('node', $node);
foreach ($w->field_objectif_bts->getIterator() as $file_w) {
  // $file_w->file returns the wrapper of the File entity. You can
  // then address it's values as:
  $name = $file_w->file->name->value();
  $mime = $file_w->file->mime->value();
  $custom_field = $file_w->file->field_custom_field->value();
  // etc. You can see all available fields by inspecting the
  // return value of $file_w->file->getPropertyInfo()
}

As far as themeing the table goes, I think your call to theme is correct (If unsure, you can check the documentation for theme_table)


Store an array in drupal 7 field I have an use-case where a large associative array is getting generated while saving a node. The array is for a specific content type. I want to save the array along with the node.

While saving all the values of an array to different fields is not practical; Should I parse the array and save it as a string to a certain field so that I can get the array back while fetching?

If so, which one would be better : serialize or json_encode.

While I heard serialize is not reliable all the time, json_encode's purpose is not the same what I am going to use.

Briefly, I want to store a dynamic associative array against a node.

Any suggestion?

serialize is better for small array, cuz unserialize will work faster. So if you work with huge data use json_encode &json_decode.
Comparison PHP Serialization vs JSON Encoding for an array  and your question already answered here on stackoverflow you can find more information about your question.


Introductory text before a view I've created an about us page on a Drupal 8 site that is a view displaying people on my site (in alphabetical order) that were generated from a custom member content type.

The page is basically a "Card" type look for each person in a 3 column grid.

What is the correct way to add an introductory block of text above this view listing? Is adding a custom block of text to the header portion the best way of doing this still? I can't seem to find any recent answers to this question. Is this easy for content editors to alter afterwords?

Under "Header" select "Add" and choose "Text area" or "Unfiltered text". Then fill in your text in the text area and click "Apply".

You will need to provide content editors access to your view in order to alter it.

Another option would be to create a custom block and to place it above the Main page content block. Then again, you will need to provide access to the content editors to administer blocks.


How to Manage Content Types I am trying to add custom fields for a Quiz Component (Multiple Choice Question). However, when I go to Home>Admin>Structure>Content types, the only types that appear are Article, Basic page and Quiz (non of the components). I can add my own content type but cannot seem to get the already existing content types to appear in this menu.

In short, how do I control what content appears on this menu.

Thanks for your help and sorry for the noob question. Just getting started out.

The admin/structure/types page lists all the content types implemented by modules, or the content type you created.
In the case of the Quiz module, there are content types created from sub-modules, such as the Short Answer module, all listed under the Quiz Question package. Once you enable the modules you need, you will see extra content types, on admin/structure/types.


Views 3 doesn't recognize a declared handler. Why not? In modules/addressfield/addressfield.module I have:

/**
 * Implements hook_views_api().
 */
function addressfield_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'addressfield') . '/views',
  );
}

and

/**
*  Implements hook_field_views_data_alter
*
* @param mixed $result
* @param mixed $field
*/
function addressfield_field_views_data_alter (&$result, $field) {
  if (array_key_exists('field_data_field_address', $result)) {
    $result['field_data_field_address']['field_address_country'] += array(
      'title' => t('Country'),
      'help' => t('The Country name of the field'),
      'field' => array(
        'handler' => 'addressfield_views_handler_field_country',
        'click sortable' => TRUE,
      ),
    );
  }
}

In modules/addressfield/views/addressfield.views.inc:

/**
 * Implementation of hook_views_handlers().
 */
function addressfield_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'addressfield') . '/views',
    ),
    'handlers' => array(
      'addressfield_views_handler_field_country' => array(
        'parent' => 'views_handler_field',
      ),
    ),
  );
}

This file doesn't get triggered in the debugger when I clear the cache. I don't understand this.

The handler is in modules/addressfield/views/addressfield_views_handler_field_country.inc which I took from the location module:

/**
 * @file
 * Country field handler.
 */

class addressfield_views_handler_field_country extends views_handler_field {

  function option_definition() {
    $options = parent::option_definition();
    $options['style'] = array('default' => 'name');
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    $form['style'] = array(
      '#title' => t('Display style'),
      '#type' => 'select',
      '#options' => array('name' => t('Country name'), 'code' => t('Country code')),
      '#default_value' => $this->options['style'],
    );
  }

  function render($values) {
      return check_plain(strtoupper($values->{$this->field_alias}));
  }
}

Any advice on how to get this to work would be helpful. Thank you.

Which core version? In Drupal 7, hook_views_handlers() is gone, add your files to your .info file instead.

files[]=views/addressfield_views_handler_field_country.inc


Where In or clause for when a variable might not exist If I were to run a normal mySQL query that selects all nodes I would do this:

set @type='node';
select * from actions where type = @type;

but what if lets say I set type to be something that doesn't exist for example

set @type='';
select * from actions where type = @type or 1=1;

This will then in return select everything regardless.

How do I do the same with db_query?

I thought just doing

db_query("select * from actions where type = :type or 1=1;", array(':type' => '')).fetchAll();

but that doesn't work. Any ideas? (notice that :type is equal to '' just like in the mySQL example)

What you need to do is take that logic out of the SQL query, and instead use the query builder so to create your query; then you can add the IN statement conditionally, e.g.

// Set up your query
$query = db_select('actions')->fields('actions');

// See if you have data
if (!empty($types)) {
  // IN is the default operator for arrays so there's no need to specify,
  // but for the sake of an example...
  $query->condition('type', $types, 'IN');
}

// Get the results
$results = $query->execute()->fetchAll();


array_shift() expects parameter 1 to be array, boolean given in include() I'm using the following to get the raw value of a field Drupal:

$foo = field_get_items('node', $node, 'field_foo');
$foo_shift = array_shift($foo);
$foo_value = $foo_shift['value'];

Which works a treat but every so often I get the following error:

Warning: array_shift() expects parameter 1 to be array, boolean given in include() (line 106 of ).

I think it might have somehting to do with checking the value is set as I only get it after going to a page where the value isn't set. But if I try to check 'field_get_items('node', $node, 'field_foo')' is set that doesn't work.

How do you mean by "that doesn't work"? The problem is likely because field_get_items returns FALSE if the field doesn't exist on that node. Checking if $foo is empty (using empty) should work.  So something like:

$foo = field_get_items('node', $node, 'field_foo');
if (!empty($foo)) {
  $foo_shift = array_shift($foo);
  $foo_value = $foo_shift['value'];
}

Alternately, because field_get_items returns false when it doesn't have a value to return, you could just put the $foo = ... line in the if statement itself:

if ($foo = field_get_items('node', $node, 'field_foo')) {
  $foo_shift = array_shift($foo);
  $foo_value = $foo_shift['value'];
}

The problem with isset is that it's just checking if the variable has a value attached to it. FALSE doesn't ping it as not being set, whereas FALSE is included in the list of values that are considered empty for empty.

The "Just to Remind" section of this posts: http://alexchernomaz.com/2014/10/14/php-empty-isset-is_null/ provides an excellent table of what values are considered empty/null/set for each function (empty, is_null, and isset), if you're interested in learning more.


Can no longer run "composer require drupal/swiftmailer" I have a module that relies on swiftmailer, and needs the libraries installed. Whenever I've needed to install swiftmailer libraries to a Drupal environment, I've always run this command:

composer require drupal/swiftmailer

This no longer seems to work. Running this now prompts me for authentication to git.drupal.org, and I don't understand why. Apparently this isn't the same as my drupal.org credentials:

I'm not extremely familiar with Composer and am wondering what I can do here.

I know you're sorted now, but wanted to suggest that this could be because the repository URL for the coder module is using https.

See here:

https://help.github.com/articles/why-is-git-always-asking-for-my-password/

The link at the bottom of that article suggests that you can cache your credentials to avoid the need to enter them when using https:

https://help.github.com/articles/caching-your-github-password-in-git/

(I would have commented rather than answered, but it seems I don't have enough reputation to comment yet!)


Custom content type displayed without theme Working in Drupal 7, I've created a custom content type "Announcement", intended to be distinct from the regular Article type. I haven't added any custom fields or anything esoteric.
The thing works, I can create Announcements and they show up as teasers in a blocks view I have set up for the purpose.
But when I click the teaser link, the announcement page is displayed as a basic HTML page - no theme. I'm using the Marinelli theme and it displays everything else just fine.
Here's the view, located in a sidebar, looks fine:

Clicking the link....

What am I missing?

I gave up in the end, deleted the content type, recreated it, and it worked. So something must've gone wrong when I first created it, but I never saw an error indication.


Adding process function in address field I am customising address field so need to add process function in address field element.

If I am using following code, then its adding process function but then I am not able to call protected function which are defined in address class in address field module.

$info['address']['#process'][] = 'custom_feature_address_element_process';

If I am using following code, then its not working.

$info['address']['#process'][]  = array(0 => 'Drupal\customaddress\Element\CustomAddress', 1 => 'customprocessAddress');

I have fixed the issue using following code.

$info['address']['#process'][]  = 'Drupal\custom_feature\Element\CustomFeature::customprocessAddress';

Naming convention was also issue.


Simplenews adds newsletters title at the top of the newsletter I have a Drupal-7 site and a testing one and a weird thing happens. When I send a newsletter from my testing site everything is ok, but when I send from the actual site, the title of the newsletter is added at the top of the newsletter. So the newsletter appears like this:
Title
Title
images , which is what I want to only appear.

Another weird thing that happens, is that the title appears only at some emails like outlook, but not on gmail or hotmail.

My question is, why do you think that this happens?Do I have to check my administrator options, or is this a code issue, like at simplenews.module file?
Thank you in advance!

Find simplenews-newsletter-body.tpl.php in modules/simplenews/theme folder.
Copy it to your current theme's folder and open/edit it. You'll see that it has a $title variable printed at the top. Comment it out and clear cache to make Drupal see your template change. Test and see the title gone.

REMOVE OR COMMENT THIS LINE =>
<?php print $title; ?>

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


How to create a includes folder inside sites/all/module/custom/ I want to create a folder name include in-side sites/all/custom/contrib/  and  inside this want to write some .inc files like date.inc, string.inc in each file a class is created which holds function.

Now I want to use this functions in each module under sites/all/custom/contrib. I have 10 custom module so this .inc functions are available to each custom module.

What is the directory structure I have to follow and how can I achieve this?

In one of your custom modules, just create a directory includes and place your .inc files inside it.

To use the .inc files in your .module file, you can use module_load_include.


Store data from a specific content type in a different database? Was not able to find a previously asked question. But is it possible and or worthwhile?

Background: setting up a new feature that will host a lot of data. Want to separate it from the rest of the site so if something happens to that data the rest of the site, users e.g will not be touched.

This is not possible without a lot of custom code. Primarily because Drupal stores field content in separate database tables. There is not the one single table that holds the content of all nodes of a specific content type. And fields are also re-usable across different content types. You would need to create your own storage engine.

Wouldn't an intelligent backup strategy be enough to assure data security in your case?


Populate Taxonomy Term reference field in node I'm using data from JSON to create new nodes on my Drupal 8 website. So, I have a createNode method that create these nodes.

Here is the code I'm using

  protected function createNode($json) {

    foreach ($json as $row) {
      $node = Node::create(array(
        'type' => 'product',
        'langcode' => 'en',
        'uid' => '1',
        'status' => 1,
        'title' => $row['title'],
        'field_code' => $row['code'],
        'field_manufacture' => $row['manufacture'],
        'field_product_type' => $row['type'],
        'field_barcode' => $row['barcode'],
        'field_packages' => $row['packages'],
        'field_pallet' => $row['pallet'],
      ));

      $node->save();
    }

  }

The problem is with field_manufacture and field_product_type, those are entity reference field to taxonomy term. I'm getting term name and I need to match it in vocabulary or add it if doesn't exist.

Any idea how to do that?

First, find the taxonomy term id by the term name as given below.

function getTidByName($name = NULL, $vocab_name = NULL) {
  $properties = [];
  if (!empty($name)) {
    $properties['name'] = $name;
  }
  if (!empty($vocab_name)) {
    $properties['vid'] = getVidByName($vocab_name);
  }
  $terms = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->loadByProperties($properties);
  $term = reset($terms);
  return !empty($term) ? $term->id() : 0;
}

Above function will return the term id and then pass this term id to your field like

// Assigning the entity reference value.
if ($tid > 0) {
  $entity->set('field_example', ['target_id' => $tid]);
}


Inline Template with Render Array in #context I'm using the https://api.drupal.org/InlineTemplate to render a string with a variable, and that variable is itself another theme function.

My reading of the documentation is that this is supported; based on the fact that the #context variable can be a string or render array.

  #context: (array) The variables to substitute into the Twig template. Each variable may be a string or a render array.

However, my implementation is not working:

    $my_subtemplate = [
      '#type' => 'inline_template',
      '#template' => '{% trans %}my {{ foo }} here{% endtrans %}',
      '#context' => ['foo' => 'bar'],
    ];

    $my_string_with_embedded_themable = [
      '#type' => 'inline_template',
      '#template' => '{% trans %}Print this string and this subtemplate: {{ my_subtemplate }}.{% endtrans %}',
      '#context' => [
        'my_subtemplate' => $my_subtemplate,
      ],
    ];

The generated output is:

  Print this string and this subtemplate: .

I've confirmed that my_subtemplate generates the correct output on its own:

  my bar here

But when its placed into a variable of another inline template, it does not render.

The issue not in the inline_template but the issue comes from {% trans %} if you place a render array variable into {% trans %}{% endtrans %} you will get the following error and it will not rendered:

  Warning: htmlspecialchars() expects parameter 1 to be string, array given in Drupal\Component\Utility\Html::escape()

So you have two options:

1) get the variable out of {% trans %}{% endtrans %} like the following:

    $my_subtemplate = [
      '#type'     => 'inline_template',
      '#template' => '{% trans %} my {{ foo }} here {% endtrans %}',
      '#context'  => [
        'foo' => 'bar'
      ],
    ];
    $my_string_with_embedded_themable = [
      '#type'     => 'inline_template',
      '#template' => '{% trans %} Print this string and this subtemplate: {% endtrans %} {{ my_subtemplate }} .',
      '#context'  => [
        'my_subtemplate' => $my_subtemplate,
      ],
    ];

2) Pre-render the renderable array variable to a string first.

    $my_subtemplate = [
      '#type'     => 'inline_template',
      '#template' => '{% trans %} my {{ foo }} here {% endtrans %}',
      '#context'  => [
        'foo' => 'bar'
      ],
    ];

    $renderer = \Drupal::service('renderer');
    $my_subtemplate = $renderer->renderRoot($my_subtemplate); // this fixes it

    $my_string_with_embedded_themable = [
      '#type'     => 'inline_template',
      '#template' => '{% trans %} Print this string and this subtemplate: {{ my_subtemplate }}.{% endtrans %}',
      '#context'  => [
        'my_subtemplate' => $my_subtemplate,
      ],
    ];


Alter behavior of Next Page > button on a multipage webform page In a multipage webform (the webform module), there is the Next Page > button. It has 2 handlers,

webform_client_form_pages
webform_client_form_submit

How do I add another one? This is because I want to change the behavior of the Next Page > button. It's behavior should depend on the value of a checkbox on the page. Or should I have to do it in another way?

Thanks,

Eric J.

webform_client_form_submit handler should be enough to use. Depends what the 'behavior' exactly is.


Issue with menu and user token I'm having problems with some links that have a user token in it.

For ex. I have a link like this: user/[current-user:uid]/edit.
But when I check this in the browser as a user I just see Edit instead of my Menu link title. I also get this error:

  Notice: Undefined index: localized_options in menu_navigation_links() (line 1861 of /includes/menu.inc).

When I check this is as an admin I see the correct title and no error.

When I change permissions of Administer users and set to all users I can see it as a user to, but that's not the way to do it because now a user can cancel his account and change the role ... .

In my search quest I've found this issue but the solution #2 didn't help much.

I'm using the Menu Token Module and these are my configurations (user is set as you can see):

These are my link configurations:

As you can see I tried the solution from the issue on drupal.org.

I fixed the problem with the following steps:

Uncheck "Use token", change the "path" to normal path without using menu token.
Save the change.
Edit the menu, check "Use token", change the "path" to [current-user:edit-url]
Save.


Add views past date filter dropdown Tried if someone has already faced or tried for this but I could not find any forum discussion around this.

Within Drupal views I am trying to add date filter based on a CCK date field. I am trying to add date filter within views like:

Past 7 days
Past one month
Past 3 months
Past 6 months
Past one year

I don't see any modules to achieve this neither any discussion around this

The Date module has a submodule called Date Views that allows Views integration with Date fields.

Once enabled, you should be able to add an Exposed, Grouped filter on your date field. For each grouped filter, you can add your Label (e.g. "Past 7 days"), Operator (is between), & Value which you can set to Relative dates that match your label (e.g. From: "-7 day" / To: "now").


Integer field with unix timestamp convert to readable date in views I have an Integer field in a content type, which contains a unix timestamp.  *(It is not a date module field; just a simple Integer field).  In a View, I am rendering this field, but obviously it is just going to spit out the long unix timestamp; and I want it to read Feb 20th, 2013.  How can I have Views format this field so that it spits out the readable date?  I imagine I would create the views-view-field--field-MYTIMESTAMP.tpl.php, and copy in the default code, then use some php logic to convert it, right?  But I am not sure how to do that part.

First you should define a suitable format- Do this in the administrative GUI:

Navigate to: Administration » Configuration » Regional and language » Date and Time
Click the tab "Formats" and click on link "Add format".
Create a new format. You use the same string as you would pass to the PHP date function, i.e.: M jS, Y. Save it.
Click the tab "Types". Click on link "Add date type".
Select the newly created format from the menu, and name it: dateonly, and save it by clicking on "Add date type".

You now have a type of date format named dateonly defined you can use anywhere on your site there is a date field to be displayed without the hour and minutes part.

To format the date in your View, you may should Drupal format_date function with 'dateonly' passed as the type of format to use (second argument). To output this in your view you may have the following in your view-view-field--fieldname.tpl.php:

<?php
$nicedate = format_date($output, 'dateonly');
print $nicedate;
?>

IMHO, there is a big advantage in first defining a standard type of date format and giving it a name.  This ensures that dates are displayed consistently throughot the site.

However, if you can't be bothered to first define the dateonly type of format, you can use custom as your second argument to format_date and then, as your third argument, pass a string that can be passed on to the PHP date function:

<?php
$nicedate = format_date($output, 'custom', 'M jS, Y');
print $nicedate;
?>


How to css Views Tree module theme I am using the module Views Tree. Apparently, it gets the hierarchical listing of taxonomy terms, and outputs a tree with indentation levels (two levels).

However, I am not able to style or css it, because the overriden tpl.php ( views-tree.tpl.php ) does not exist, and when I copy views-view-row.tpl.php in the theme folder, renaming the file to views-tree.tpl.php I almost get it, except that the rendering is: first the parent taxonomy terms, and next the children terms. Exactly as without the module.

So I am unable to use none of the available .tpl.php for Views, and cannot change the style, only with css, which is not adequate (there are ul tags which I want to have different classes, for example).

So, sadly, I must use template.php and views_get_view_result to recover the View and css it, which is exactly as not having the module installed at all! What am I doing wrong?

Finally, I discovered that the module uses the core listing resources, so the theming can be achieved via template.php and function NAMEOFTEMPLATE_item_list($variables). The only caveat is that, as the call to this function is recursive, you will need some tricks to know in which level you are. Those tricks could depend on the listing itself; another solution would be to modify the module itself to send the level.

Honestly, I think this in an example of a module whose existence is questionable. A direct treatment of the View_results is much faster and easier to theme.


Page redirect with condition I want to redirect the users to a particular page when they view a certain page when there are some conditions. The condition is that the user has uploaded a node, for example an article.

Say there are two pages, Page A and Page B.

Page A Link <-- if the user has not uploaded a node, clicking on this link will take him to Page B

I have installed the node limit module which allows the user to upload only one content.

It seems you can achieve that using the Rules module.

  The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.


How to make my validateForm working? In a custom module of mine, I have two custom entities A and B with a one to many relationship from A to B.
This is Edit form for EntityB:

I want to have this check in validateForm: if 'Contact' (boolean) is checked, 'Adhérent' (entity_reference to EntityA) shouldn't be empty.

Here is my validateForm:

  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $values=$form_state->getValues();
ksm($values);
    if ($values['estlecontact']['value']==1 && $values['adherentid']['target_id']==NULL) {
      $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));
    }
  }

In this case, I should not have the error message and still...
What am I doing wrong?
Here is the result of ksm:

I figured it out!
this works:

$values=$form_state->getValues();
if ($values['estlecontact']['value']==1 && $values['adherentid'][0]['target_id']==NULL) {
  $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));
}

Note that $values['adherentid'] is a mutliple value field. I was missing an array level. Adding [0] before accesing target_id solves the problem.


Drush from GitHub stopped working I have a Github clone of drush that has been working since it moved there.  I did a git pull this morning, and am now getting errors:

  $ drush

  Warning: require(/home/mpd/drush/vendor/autoload.php): failed to open
  stream: No such file or directory in
  /home/mpd/drush/includes/bootstrap.inc on line 1007

  Fatal error: require(): Failed opening required
  '/home/mpd/drush/vendor/autoload.php' (include_path='.:') in
  /home/mpd/drush/includes/bootstrap.inc on line 1007

How can I fix this?

Drush now uses composer for managing external libraries.  You can read about this in the GitHub issue.

If you don't have composer installed, you can follow the instructions on its project page.  Under Linux or OSX, you can do

$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer

which will install it globally.

Once you have done this, you can

$ cd /path/to/your/git/clone/of/drush
$ composer install

This will download all of the external depencencies, and drush should start working.

See the drush project page for details.


Add link to topic list after new topic or comment submission I would like that, when users submit a new topic or posts a reply in a forum, they would be redirected to the topics list.

How can I do this?

There's count of ways to do it, one of these: Rules module. Just add condition on node or comment adding, and add action for redirecting. For taking correct forum page of node or comment, I assume you should enable "php filter" and add php code that got forum taxonomy term and redirect to certain page.


Views: How to list "files" view for their own files? I'm working on Workbench module on Drupal 7. There is a "File List" tab and showing all images and files from the site. I would like to change this to be showing their uploaded files only.

PS: the "File List" Tab is from the "workbench_files" Views

First open the workbench file tab, then from the contextual menu on the right select edit view.

Add the relationship 'The user that uploaded the file.' if it does not already exist.
Above Relationship, you will see Contextual Filters (these are dynamic contextual parameters you pass to views). Add a contextual filter 'The User ID' and set the relationship to 'User who Uploaded'.

In the same window just below that there is a section 'When the filter value is not in the URL'. You select 'Provide default value'. This opens a select list, from which you choose 'Use ID from logged in user'


How to add an HTML comment to the head of every page? I'm looking to add a copyright message to every page of my website using Drupal 7. The easiest way to do this would be to add it into the header, since that appears everywhere. I know that changes can be made to html.tpl.php.

But I'm unfamiliar (for now) with php, and need to know if I need to add any special commands to the php or can I just inject my comment into the file?

You're better off using a more Drupal-centric solution. If you're looking to place some static copyright info, you can create a block of HTML and place it in a footer region of your site's theme (under the block administration area).

If you're just looking to play around with the Drupal CMS & PHP coding in general (off topic for Drupal Answers), as long as you make your changes outside of the <?php ?> tags you should be fine to make changes to your template file.


How to download files which are stored in the folder I need some guidance regarding how to download a file.

Suppose I have a link called "Download." When I click on the particular link a PDF file should be downloaded.

How can I do this?

Make the link point to the PDF file
Make sure that the PDF is public accessible.


Create / publish a node via sms I have successfully installed sms framework module and configured with envaya gateway. I have support ticket module. I need to allow the users to create ticket (node:support ticket) via sms. Could you please guide me how to accomplished the same.

Normally the SMS gateway will ping a URL on your site with the relevant details from the SMS, e.g appended as a GET querystring.

I've done this before with hook_menu and a custom callback to listen for the SMS details.

/**
 * Implements hook_menu
 */
function MYMODULE_menu(){
  $items = array();
  $items['api/sms'] = array(
    'title' => 'SMS listener',
    'page callback' => 'mymodule_sms_incoming_process',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;

}

/**
 * SMS listener
 * Processing incoming SMS messages
 */
function mymodule_sms_incoming_process(){
  /* Do stuff with SMS parameters
   * Make sure to sanitize any $_GET vars with filter_xss etc..
   */
  if (!isset($_GET['code']) { return FALSE }
}


Export block content in drupal 8 I have made my custom block content. I created a block with it and I assigned it to a region.

How can I export the actual block content not the block type?

One of these contrib projects:

default_content - for install profiles
entity_pilot - paas content staging (disclaimer, my product)
deploy

Or build your own deployment with rest API


Updating custom modules I have a module I wrote that is used on a production site.  I had to make some changes and need to update the module.

Where do I begin to learn to do this?

"Updating a module" can comprise of two things:

If it's just code, then simply replacing the old code with the new code should be sufficient. However, when your code is complex or you are working in a multi-user environment, it is best to bring your code under version control like svn or git (as you have tagged), and maintain it with branches and tags depending on the version of Drupal that you are working with.
If your module also involved database updates, then you will need to become familiar both with the .install file as well as hook_update_n() functions. The documentation for the latter along with source examples from the .install files of core modules should guide you to creating update functions correctly.

On a related note, if your custom code is generic enough to be of use to the rest of the community, you can post it as a Drupal project and leverage drupal.org's project management feature which comes with git access.

You should also test everything out on a development server rather than on the production site. Adding lots of documentation to your update functions as well as maintaining a CHANGELOG.txt is also recommended.


how to let a form field be hidden and at the same time the value be able to acces the id using javascript? How can I get the #value of a hidden form field in javscript as for hidden form field I am unable to get its id in the (inspect element) html.
How can I extract the value(#value) for the field using ajax for the hidden fields

Try this:

$form['hidden'] = array(
 '#type' => 'hidden',
 '#value' => 'Your_value',
 '#attributes' => array('id' => array('your_id')),
);

Now using javascript or jquery you get the value of the hidden field.

In jquery:  jQuery("#your_id").val();


Update.php does nothing I'm trying to do a minor security upgrade to Drupal 8.1.7  When I load update.php it gives me a blank page (no errors).

I upgraded all of the software with the exception of the root .htaccess and robots.txt files.

I'm getting this error:

  PHP Parse error:  syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or '(' in /home/energy/public_html/index.php on line 11

The line causing the error is the following one.

use Drupal\Core\DrupalKernel;

Drupal 8 requires PHP 5.5.9. If you are using PHP 5.2.9, it doesn't recognize as valid a line like use Drupal\Core\DrupalKernel; since namespaces were introduced in PHP 5.3.

If you were already running a stable release of Drupal 8 before, check you didn't change in someway the PHP version used from your site.


Date formatting: Code or Template? A theory/best practice question as opposed to a technical one. Should it be up to a module's code to format a timestamp into a date string, or the template that displays it?

E.g. the two ways of doing it (both with the same result):

MYMODULE.module

$variables['date'] = date('m-d-Y', $timestamp);
return theme_render_template('template.tpl.php', $variables);

TEMPLATE_FILE.tpl.php

<?php print $date; ?>

Or:

MYMODULE.module

$variables['date'] = $timestamp;
return theme_render_template('template.tpl.php', $variables);

TEMPLATE_FILE.tpl.php

<?php print date('m-d-Y', $date); ?>

Instead of date() you should use format_date() instead per Drupal.

https://api.drupal.org/api/drupal/includes%21common.inc/function/format_date/7.x

format_date takes various settings and user config into account when formatting the date, whereas just date is a php function, and thus, will not. You can also pass it a custom date format name.

While you can use format_date() at the template level, usually it is best to do it in a preprocess function and pass it along to the template. If you have a module that is supplying variables to a template, supply them upfront.

Variables should be print-ready for the user, with the option of overriding later (extending or preprocessing at the theme level, etc).


Upgrade Drupal 6 to 7 using Drush 5 in Windows Drush 4 has a site-upgrade command for major version upgrades.

Looking at Drush documentation pages, and it looks like the command is not a feature in Drush 5. Is there a replacement or was it removed? I'm using the windows version of drush 5.

That functionality is now available as a separate module: Drush Site Upgrade

  The new home for site-upgrade drush command, which streamlines the major version upgrade process for Drupal.

There's also some reassurance that this will work with the latest version of Drush:

  IMPORTANT: Drush Sup 7.x-2.x requires Drush 5 or later.


how to avoid fieldset in drupal date field I have a date field in registration form, I am using template for that. When I using  its outputs the html with fieldset. How can I remove that I wanna style likebleow fields.

Please see the image

Its drupal 7

Use the latest full release or the 7.x-2.x-dev version of the Date module.

There is an new option Render as a regular field available there:

The option was added at the Make it possible to disable fieldset for date field issue.


Fresh install with minimal: missing manage display even with field_ui turned on I just installed a fresh copy of Drupal 7 and chose the minimal install option. I enabled field_ui and I still do not see the manage display tab on content pages. However it does show up when you goto the content type directly. Did i forget to click somewhere?

For displaying Manage Display tab on content page you have to install Display Suite module.

On drupal core no such module or configuration  that display this tab on content page. So you didn't forget anything for this.


title_prefix override to h1 instead of h2 How do I override the $title_prefix that is inherited from the value of

    <h2<?php print $title_attributes; ?>><?php print $title; ?>

in panels-pane.tpl.php page. This is normally output in the page.tpl.php but since i'm using panels it becomes the above.

My stating attempt is to write a template.php preprocess function, but this adds the code to every title in the template, and just adds the h1 to the page; it does not replace the h2 with the h1 for each page title. I don't want to touch the $title value which is h2 but change $title_prefix.

// Preprocess title prefix override. h1 instead of default h2
function at_panels_everywhere_preprocess(&$vars) {
  $vars['title_prefix'] = array(
    '#type' => 'markup',
    '#markup' => '

',
  );
}

I need to replace the $title_prefix ouput to be h1 not h2 and only for the title_prefix while within the #content region.

Potential solutions that didn't work:

http://drupal.org/project/panel_variant_page_title
Changing panels-pane-tpl.php h2 to h1 as this changes all panels not the 1 page panel that needs to be h1.

Eventual solution:

Turning off Page panel titles and just hardcoded h1 tag into body field. Not ideal but there really is no working solution apparently.


Upgrading procedures and what essential directories to copy over? When I upgrade my Drupal 7 core I do the following process:

Download and unzip d7 release as d7_upgrade
Delete the sites folder in the d7_upgrade
Move the sites folder from my original site into d7_upgrade
Rename the old D7 folder to d7_old
Rename the d7_upgrade to original folder name
drush updb

Majority of the non-core files reside in /sites for D7.

I know D8 has a different structure, but is the same upgrade process going to be the same? I know I would have to move over /themes /modules /sites

Is there anything else I need to move over? Or is there a better method of doing this? I want to upgrade to D8.3 beta to test on my site.

As Kevin has stated in the comment, the "official" procedure should be found here, and it's ever evolving. I don't believe any safe automated way currently exists 100% of the time (such as with Drush/Drupal Console/Composer/etc.)

In short, upgrading D8 sucks. At least as far as I can tell. If you plan on using composer with it, you can't rely on "drush up", lest you want it all to get wiped, etc. (Actually, I'm kind of confused as to why you're not using "drush up" on your D7 sites, since you clearly have drush installed.)

In short, the process is still very similar to what you're already doing with D7. The file structure has changed in D8 though, and you need to be aware of things like modules/themes/libraries being in the root directory, rather than the sites/ directory. All that is covered in the documentation.