Unanswered Questions only show for admins I am using the Answers module to configure a discussion feature on our website. The view, which shows the list of questions as well as answers, is only showing questions which have been answers but not unanswered questions, except for admins, who can see all of them. Once the question is clicked, any user can provide an answer.

I cloned, edited and disabled the original view. I've made sure that all authenticated users are able to view published nodes, create questions and add answers.

I've installed this module in a separate sandbox site which is completely stripped to the bare bones and it works as designed, everyone can see all questions.

Customizations I have made to the view include, changing from table to unformatted list format, and bringing in various fields. This screenshot shows the version I created which populates the view with questions and answers, however, this issue was going on before I made that customization.

I'm using Answers version 7.x-4.0-rc2

Edit: I have installed this module in a fresh sandbox with no customizations and it works perfectly so I know it's something I broke.

See the exported view. Note "Debugging page" is a simplified version that still has the problem. Please use that page when debugging.

Apart from the customizations you described (within your "customizations I have made ..."), you also seem to have customized the 2nd (last) filter that you're using: it says "(in Answered ...)", while in your exported view it shows the machine names of content type "Question" and content type "Answer". While the view shipped with the Answers module (disclosure: I'm a co-maintainer of it) uses ONLY the "Question" content type.

I suggest you adapt that 2nd filter back to how the shipped version looks like, i.e make that filter only check for nodes of content type "Question". And if you then need any other data (columns in your view) specific to the "Answer" content type, those should be made available via the 1st relationship (entity reference) you already have in place (and which still matches the shipped version).

I'm not yet sure if this is the only change you'll need, but at least it will get you closer to the view you're trying to create (depending on possible updates to your question, I might further improve my answer afterwards).

PS: I noticed you also turned of "aggregation" (another customization). Not sure (yet) if that has anything to do with your issue.


Module Installation: Unable to create directory 'temporary://update-extraction-f781a69c/ I have searched the answers on this site and have found threads like
    Configuring the temporary directory which refer to this issue but could not arrive at a solution. My setup is Linux (Fedora), Apache, PHP 5.4.22 with Drupal 7.24 and I've done the following to ensure a correct configuration of the Drupal file tree:

1) chown -R apache:apache Drupal
2) cd Drupal
3) mkdir tmp
4) chmod 777 tmp
5) Change temporary directory in drupal admin/config to "tmp"

When I try to install a module (either through direct file upload or via URL) I get the error:

Module Installation: Unable to create directory 'temporary://update-extraction-f781a69c/

Now, the curious thing is that when I look in Drupal/tmp I see the following:

[root@localhost tmp]# ls -l
total 1448
-rw-rw-r-- 1 apache apache 1476650 Dec 13 23:24 bcommerce.tgz
drwxr-xr-x 2 apache apache    4096 Dec 13 23:24 update-extraction-f781a69c

So the extraction folder is created and seems to have proper ownership and permissions yet I'm still getting this error.

I've also ensured that the files in my tgz archive have proper permissions and are owned by apache, so their permissions should also be OK.

Any ideas on what might be wrong here would be much appreciated; I've been banging my head against this issue for a few hours now and have gotten nowhere.

For me, things like these were caused by selinux. Either disable it, or add appropriate policy:

grep httpd /var/log/audit/audit.log | tail -n 50 | audit2allow -M drupaltmp
cat drupaltmp.te

Look inside, may be tune a little. I've got this:

module drupaltmp 1.0;

require {
        type httpd_t;
        type var_lib_t;
        type etc_t;
        type etc_mail_t;
        class file { write setattr };
        class dir { search create getattr setattr };
}

#============= httpd_t ==============
allow httpd_t etc_mail_t:dir { search getattr };
allow httpd_t etc_t:dir setattr;
#!!!! This avc is allowed in the current policy

allow httpd_t etc_t:file { write setattr };
allow httpd_t var_lib_t:dir create;

Then install it inside selinux

semodule -i drupaltmp.pp


Select DISTINCT on a particular field I want to return distinct values based on a particular column - 'company_code'. How do I achieve this? My code is as below.

$query = \Drupal::database()->select('actuarial_bases', 'bases')
                    ->fields('bases', ['company_code','basis_id','mortality','commission','initial_expenses','recurring_expenses','date_saved','discount_rate'])
                    ->condition('approved_by',!"")
                    ->orderBy('date_saved', 'DESC')
                    ->distinct();

My online research led me to this page.

I created a view to include 'row_count' using the following query:

SELECT
    `company_code`,
    `basis_id`,
    `mortality`,
    `commission`,
    `initial_expenses`,
    `recurring_expenses`,
    `discount_rate`,
    `date_saved`,
    (
    SELECT
        COUNT(0)
    FROM
        `actuarial_bases` `b`
    WHERE
        (
            (`a`.`date_saved` <= `b`.`date_saved`) AND(
                `a`.`company_code` = `b`.`company_code`
            )
        )
) AS `row_number`
FROM
    `actuarial_bases` `a`

then modified my query to:

$query = \Drupal::database()->select('bases_in_force', 'b')
         ->fields('b', ['company_code','basis_id','mortality','commission','initial_expenses','recurring_expenses','date_saved','discount_rate'])
                    ->condition('row_number',1)
                    ->orderBy('date_saved', 'DESC')
                    ;
$results = $query->execute();


How to handle config changes on core update? I have an 8.6.15 site managed by composer and drush. The db and config exports are in sync.

Roling our new features using drush cim on production works fine.

I now update core to 8.7 by running copmoser update and drush updb successfully, and everything seems to be working as expected.

The update process causes configuration differences between the db and the exported config files

My question:
What is the proper way of handling these config changes?

1) drush updb -> drush cex (seems logical to me)

2) drush updb -> drush cim -> drush cex

The two strategies result in slightly different end configurations.

Schema updates in different versions of core and contrib which cause changes to the config will cause an issue where your config becomes outdated.

On your local environment, run:

drush updb
drush cex

Then you can commit and push your configuration, and on your target (i.e. production, or stage, etc) environment, run:

drush updb
drush cim

Failure to do so will cause hard-to-diagnose issues in some case. More info and examples at:

Update hooks which modify configuration can lead to unstable sites; figure out how to deal with this.


How do I set some script in the  section on a page? I solved some question on field type generation and learned how to render my custom field.
Now, I need to use an accessible audioplayer to play my songs. In my custom field formatter view function I set item_output to render this custom field in an unordered list. Each item of this list is a link that calls a javascript function that plays automatically the song.
Unfortunately, to use this player, I must set some script in header section of my page, and style css for this player.
So, I need to set these scripts on ly in a page that displays this field. There is a way? Maybe in $element array returned from field formatter view function?
I hope you can understand me, my english is very bad!

The function drupal_add_js can solve your probleme.
You can try this in custom module:

function my_module_init() {
     drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/my_file.js',
        array('type' => 'file', 'scope' => 'header', 'weight' => 1000)
      );
}

Look at this documention for use this function in diffrent way.


If two modules both defined the same menu path in 'hook_menu', which one Drupal will choose? For example, "moduleone" defines the path 'admin/hello', which output print_moduleone_stuff().

/**
 * Implements hook_menu()
 */
function moduleone_menu() {
  $items['admin/hello'] = array(
    'title' => 'Module One Hello World',
    'page callback' => print_moduleone_stuff,
  );
  return $items;
}

"moduletwo" defines the path 'admin/hello', which output print_moduletwo_stuff().

/**
 * Implements hook_menu()
 */
function moduletwo_menu() {
  $items['admin/hello'] = array(
    'title' => 'Module Two Hello World',
    'page callback' => print_moduletwo_stuff,
  );
  return $items;
}

Both modules defined 'admin/hello' path for different result. With these two module enabled, how does Drupal select one than another? How does Drupal solve the conflict?

The function invoking hook_menu() is menu_router_build(), called by menu_rebuild(). It contains the following code.

  foreach (module_implements('menu') as $module) {
    $router_items = call_user_func($module . '_menu');
    if (isset($router_items) && is_array($router_items)) {
      foreach (array_keys($router_items) as $path) {
        $router_items[$path]['module'] = $module;
      }
      $callbacks = array_merge($callbacks, $router_items);
    }
  }
  // Alter the menu as defined in modules, keys are like user/%user.
  drupal_alter('menu', $callbacks);

If there are two modules defining the same route, the last module in the array returned by module_implements() will override the value defined from the other modules.

The second parameter required by module_implements() is defined as:

  $sort By default, modules are ordered by weight and filename, settings this option to TRUE, module list will be ordered by module name.

Since menu_router_build() doesn't pass the second parameter to menu_implements(), the function is using the default value for that parameter. This means the list of modules are ordered by their weight and filename; when two modules have the same weight, the first module that appears in the list is the one that alphabetically comes first.

Furthermore, any module implementing hook_module_implements_alter() can alter the order the hooks are invoked.

For this reason, you should not assume to know in which order the hooks are invoked.
If the purpose of the code is altering the route implemented by another module, for example because a route should be removed when a second module is installed and enabled, the code should use hook_menu_alter(). If you are trying to understand which module would "win" in the case of route conflicts, I would rather avoid such route conflict, and define a route that is not already defined from another module.

If then you are implementing hook_menu_alter(), and you want to be sure your module is executed last, to be the module that effectively overrides a route, you should implement hook_module_implements_alter() too.

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // Move mymodule_menu_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}


Hide conditionally hidden fields from custom node template Case: I am using conditional fields module to hide some dependent fields based on the value of its dependee field. I have created a custom node--content-type.tpl.php template for my content type.

Field1

Field2

Here, Field2 is dependent on the value of Field1. Suppose in this case, Field2 is rendered only if Field1 has value 'jobs'. Otherwise, it is hidden from both node edit form and node page.

When using seven theme and its display(default or teaser) to view node, if the Field2 is hidden or the dependency was not triggered the Field2 is not rendered on the node page, which is correct.

But, when using my custom template, I am not been able to prevent the rendering of Field2 on my node. It is shown with its default value on the node.

Please help.

template code:

<?php if(isset($content['field_job_type'][0]['#markup'])):?>

Job Type: <?php print $content['field_job_type'][0]['#markup'];?>

            <?php endif;?>

Based on the comments:

generic template works, but custom does not

custom template overrides visibility rules

I would surmise that the problem is with the visibility, since the conditional field is likely only hidden, and not actually being removed - this would cause the code to execute every time, while in a standard render() it would remain hidden
Using Devel and specifically the dpm() function, I would find the element in the field array that manages the visibility of the field and use that as the basis for the if statement.

A suite of modules containing fun for module developers and themers


How do I migrate the content of a specific type? I wanted to backup all the contents of specific content type, and I want to install those data in different machine. Can anyone suggest me some good module which could help me do this?

I have tried the Backup module, and the Migrate module, but they back up the entire database. I want to backup specific contents alone but I couldn find any modules to do that.

I could use either the Node Export module or the Feed module to back up specific content. Node export gives various options like you can export the data to CSV, XML or in text format which can be then imported using node import.

If you can get a CSV of the particular nodes you wish to migrate, then the Feeds module will do exactly what you want.

Worst comes to worst you can generate an RSS feed in Views of the content on your original site and then import using Feeds to the new site from that RSS feed.


Implement hook_token_info and hook_tokens I am trying to create custom tokens, but my implementation doesn't work.
I have implemented hook_token_info() and hook_tokens() like this in my .theme file for Drupal 7.

/**
* Implements hook_token_info().
*/
function THEMENAME_token_info() {
  $info = array();

  $info['types'] = array(
    'commerce-order:commerce-customer-billing' => array(
      'name' => t('Commerce Order Billing'),
      'description' => t('Global commerce order billing tokens'),
     ),
  );
  $info['tokens'] = array(
    'commerce-order:commerce-customer-billing' => array(
      'address-info' => array(
        'name' => t('Commerce address information'),
        'description' => t('Token for commerce address information'),
      ),
    ),
  );
  return $info;
}

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

  if ($type == 'commerce-order:commerce-customer-billing') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
      case 'address-info':
        $address_info = theme('nr_commerce_address_information', array('order' => $order));
        $replacements[$original] = $address_info;
        break;
      }
    }
  }
}

When I see the list of available tokens in the interface, my tokens does not show up. Why? Is there anything wrong in my code, or is the reason another one?

I found out. It was because I tried to implement hooks in my template rather than doing it in my module.


Rotate through views result weekly I have a content type called "Tips of the Week" and in a Views block. I would like to display one tip at a time, but have it display the next tip in a week's time based on the content's post date. If a tip is added, it is entered into the rotation of the tips.

A tip might not be added every week, so I do not think it can be solely based on the post date of the tips. Instead, is there a way to cycle through the offset.

I have tried different sort criteria, and the closest one I could find was random, but that changes every time the page loads.

How can I accomplish this?

Thanks!

Add a date field to your tip of the week content type.  That date field will indicate when the tip becomes visible on the site.  Order your view by date (descending), and filter out all entries where the date field is greater than the current date.

If you want to write some code, you can add a hook that runs when you submit the form, and, if you leave the date field blank, have it select the maximum value of the date field out of the database, add a week to that, and fill the date in automatically.


How to combine two node/add/* forms into one form but create two different types of content in drupal 7 on submitting it? I want to combine two content/add/* forms into one form but create two different types of content in drupal 7 on submittiing a single from.

My initial thought on a solution was also entity reference and entity inline form but a few caveats regarding the latter. The enitity inline form adds a submit for the additional content type, this seems against your proposed UX so you will need a hook_form_alter to change this behaviour (and indeed the label)  have a look at http://drupal.org/node/1880850 for a solution I worked on that will give you a lead in (but not a solution to) this.

The other issue is that I got a lot of annoying but non-fatal and non-damaging errors when I loaded entity inline form so stability may not be 100% there. This could be an issue.


Implementation of the Google Identity Toolkit (openid like) I´m trying to weite a module that implements the folliwing google api
http://code.google.com/apis/identitytoolkit/index.html

it´s kind of like the openid, uses external accounts from the api to allow users to login without having to register the anoying long register form and pass through all verification

I´m new to D7 and openid conpcepts, what i´ve tested was the openid module that comes with D7 and got very disapointed...

first of all I had to have an openid url then I had to create the user and aprove my validation link from my email in order to get logged in to my drupal

that´s useless... because I went through basicaly the same process

What I want is something similar as this StackExchange experience, I used my gmail account and got logged in, I only had to login to google and that was it...

Any ideeas from where to begin with the implementation ?
I want to be able to sync automaticaly the users that will use the Google Id kit with Drupal, without asking too many questions.. because after all what I´m interested is them be able to leave a trail on my site but do encourage them to register easily...

update:

found on google documentation this page
http://code.google.com/apis/identitytoolkit/v1/drupalsample.html

If you want to implement it in specific open source platform, please use Google Identity Toolkit Plugins. There is a plugin for opencart 1.4.x: http://www.opencart.com/index.php?route=extension/extension/info&extension_id=3302

It only asks you for 3 installation steps without any coding work to make your dream become true! =)

Drupal plugin for it will be alive soon.


Get file ID and path to use in View template I am working in my Row style template (views-view-fields--MYVIEW--block-1.tpl.php). I need to get the file ID and path of an image. The image field is a multi field, so I need to get all of the images for each row. How do I do this?

I also will need to get the delta value of each image.

I try using kpr($variables) but I can't click to expand:

The THEME_preprocess_views_view_fields(&$var) function in the template.php in your theme directory is get called just before loading the Row Views Template file. Every component of the current row is saved inside the $var array.

To get what you need, simply just kpr($var) and it gives you all of the information about the current row. You can also save these information in the $var array as an index and use them later.


How do I remove product duplicates in a view? In my view I have duplicate entities for my product list, this is different from Drupal 7 as you could use the distinct module.

How can I remove the duplicates from my commerce product views in Drupal 8?

Drupal Commerce has duplicate entities because a product is referenced from multiple variations, any field you add to a variation type will find multiple duplications in your view most notably in images but could be any field in example t-shirt size.

An easy way to remove these is to set in your view:

FILTER CRITERIA
Product: Variations:delta (= 0)


Moving elements to other page regions I want to move the page breadcrumb to the content region in Bartik (D7.)

I assume it is theming but I can't find anywhere (style.css, layout.css) where the breadcrumb is assigned in the first place.

Does anyone know how to do this?

Thanks. :)

I will again answer my own question here:

The change is made in the page.tpl.php template found the the template directory of your theme.

In this case, all I had to do is move the following:

<?php if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

<?php endif; ?>

from it's present location under the main-wrapper to its new location under the content heading. Then I cleared the theme registry cache.

Make sure that if you move an "if" statement, that you always move its corresponding "endif" statement too.

:)


Feeds tamper to find element in text and replace it with part of the element or 0 I have a set of HTML pages that I'm importing (regularly) into a Drupal site using Feeds and Feeds Tamper.

One of the elements in the feed can take one of two forms:

Birth 1869 Location Merthyr Tydfil, Glamorgan, WalesG

or

Marriage Calculated 1894 (i.e. without a Location section).

The feed contains an unlimited number of these elements which will be imported into a multivalued Field Collection attached to a node.

I need to extract part of the Location section (a latitude) or if there is no Location provide a default value of 0.

I'm using the Find Replace Regex plugin to extract the latitude and add a pipe character (to allow me to Explode the results into an array).

My find regex currently looks like:

.*?Location.*?"gs-pl".*;q=(.*?),(.*?)".*|.*

which either identifies the latitude or returns the full string if there is no Location element.

My replace regex looks like:

\1| which works fine for the case where the Location element exists.

However, I can't see how to replace any empty string returned (i.e. when the capturing group is emtpy) with a figure 0.

Is this possible using the Find Replace Regex plugin, on its own or in combinations of other tampers as well? I wondered if I could process the original element to add a Location element with the values required as a default if it was missing but that still involves a conditional replacement so it's essentially the same problem.

I can't set insert missing Location elements in the HTML before the import, and setting the default value in the String Collection doesn't work because of the way field collections are imported (basically the method I'm using puts the data in the wrong field collection item if there are any empty fields)

You can add a Tamper plugin of type "Set value or default value". Set "Value" to "0" and enable the "Only if empty" option (see image below). This way, the value "0" will be set only if the "Find replace REGEX" returned an empty result.

I tested with your example data if this would work and in my case it did.
Birth 1869 Location Merthyr Tydfil, Glamorgan, WalesG resulted into 51.7479 and Marriage Calculated 1894 resulted into 0.


How to make a MENU_LOCAL_TASK on a user's profile only appear on their profile? I use logic like this to place a tab on each user's profile page so users can view analytics from the usage of a WebApp:

  // maps a url to a sub-page of user's profile, url to user's Analytics-Management form
  $items['user/%user/ClientCompanyName'] = array(
    'title'            => 'ClientCompanyName',
    'description'      => 'Manage your ClientCompanyName services.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('_ClientCompanyName_mgmt_form'),
    'access callback'  => 'user_access',
    'access arguments' => array( 'access ClientCompanyName services' ),
    'type' => MENU_LOCAL_TASK,
  );

This works great for each user, but I do not want one user to be able to go to another user's profile and hit their link to get to that other user's private analytics data.

Currently, if a user tries to visit another user's analytics management page, they see an access denied page.

But I would like them never to even be given the link to that page. I tried writing my own 'access callback', but I can't figure out how to pass in the '%user' portion of the intended url so I can test that against the logged in user...

I like how one can use '%' symbols in the url, and then 'page arguments' can be used to reference those arguments in the url. Is it possible to do something similar with the 'access arguments'?

Essentially, I'm trying to achieve the same thing as the behavior of the 'edit' tab on a user's profile: only if the user is on their own profile page will that 'edit' tab appear on the profile. How do I get the same effect for my WebApp analytics page?

(I guess I could make my analytics page a MENU_LOCAL_TASK of the profile edit form... but I'd still like to know how to create a conditional MENU_LOCAL_TASK whose conditional is more then simply an user_access() permissions test.)

Instead of user_access, define your own access callback function and then pass the user object to that.

So 'access callback' => 'yourmodule_analytics_access' and 'access arguments' => array(1).

In that function, compare the user id and check the permission.

function yourmodule_analytics_access($account) {
  global $user;
  return $user->uid == $account->uid && user_access('access ClientCompanyName services');
}


How does upgrade checking work? I am new to Drupal. I first created my site in Drupal 7, but I had to use Drupal 6 because a lot of the modules I use were not ready yet.  Now I'm noticing more and more modules are having development releases for Drupal 7.

If I install a development release, will the upgrade manager notify me of updates once it's listed as the main module or will I need to switch to the main module to keep getting the notification?

If you install an official dev version (not a git checkout, but downloaded from the website), it has a date information. If there is a newer stable or dev version, you will be informed.

However, development releases are exactly that. Some work, some work well and others might not work at all.


Holistic Design Critique for a Volunteer Matching Service I'm a new Drupal developer, and  I made an initial implementation of a project, but some of the things that I'm doing probably aren't the best solutions, so I was hoping to get some critiques of my design.  What the site will do and how I'm doing it is below.

The motivation:

I'm making a volunteer matching service in Drupal 7.  Specifically, community representatives from nonprofits can point our service to their issue tracker (ie, GitHub), we'll turn their issues into nodes, they can organize those nodes, and volunteers can sign up to work on some of those issues.  Also, those volunteers will belong to an organization with a Corporate Social Responsibility (CSR) representative, and the CSR representative can administer their volunteers (email them, modify the tasks that they signed up for, etc).

The implementation:

Community managers are a user type.  I use profiles2 and fields to give them an issue_tracker_url that they can store in their profile.  I implement hook_menu to add a link to their profile that they can click to grab issues from the issue tracker based on their specified issue_tracker_url.  The function that pulls stuff down from the issue tracker is the callback in hook_menu.

"Issue" is a custom node type that has some fields like the issue's id within the issue tracker so that we don't get duplicate nodes if the nonprofit pulls issues multiple times.

Each community manager can have several projects.  Each project can have smaller sub-components.  The issues from the issue trackers all belong to a given sub-component.  The community manager should be able to manage which issues are in each component, which components are in each project, and which projects are in their organization.  Allowing them to create nodes of each type and organize everything in a book would work, but it seems like a kludge.  Taxonomies seem like they might be a more elegant solution, but I wasn't sure how to get one set up for what I'm looking for or how to let the community managers manage their own organization's taxonomy.

The volunteers also need to be able to view using this hierarchy.  That is, they should be able to see a list of all organizations (all community managers).  An organization page should have a list of all projects; a project page should have a list of all sub-components; a sub-component page should have a list of all issues pulled from the issue tracker that were organized into that component.  I have tried using a view with filtering, but I haven't found a way to do that so that it will automatically generate pages based on the hierarchy described above.

I haven't yet figured out how to set it up such that the CSR representatives can manage volunteers from their company.

All of this should be easy to setup in case we want to have multiple instances of this service.  Thus, the manual setup stuff involved in setting up the views and fields should be automated.  Could I use the features module to automate this?

I have tried to do as much of this as possible using existing modules for the sake of maintainability, but if any of the functionality that I'm describing doesn't exist well in an existing module, I'm perfectly comfortable programming it myself.

Thanks for reading through my lengthy description and for your critique!

This type of question is very difficult to respond to. It is very broad and potential responders do not know enough about the details to make sense of the best strategies to use in structuring it.  I suggest that you continue expanding the story you have begun here including flow diagrams for how the user would enter, organize and use the information. Since Drupal is basically a big database management system, think about the database structure  that would make sense to hold the information.

You will contain most information in content types with associated fields to categorize the content.  Fields are often associated with taxonomies which add the benefit of creating organizational hierarchies.  They provide a simple way for users to enter and categorize their information effectively and uniformly. You can also organize taxonomies into hierarchical menus (Taxonomy Menus) so they can quickly access information they require.

Views is basically a UI for SQL queries, so you will use that to retrieve and organize information to meet the users needs. For instance Views can be set to respond to taxonomy menus to arrange complex collections of content.

The easiest and most flexible way to arrange your information on a page is to use Panels and Page Manager(Ctools).  They allow you to intercept any URL request and arrange the content in multiple ways depending upon the context at the time it is called.  For instance, you can alter the content on a page and rearrange how it is displayed based upon the permission level of a user.  By adding Panels Everywhere, I have managed to practically totally bypass the theming system and the complex styling spaghetti it can produce and simplify my style sheets and gain better control of what is displayed.

Features is a great module for exporting parts of a site to other sites.  It is complicated and not perfect, so I would recommend getting one site solved first and deal with features later if you can.

I have had some problems with Profile2 and do not believe it is ready for prime time yet (it is a fairly new module).  Most basic profile information can be easily handled by adding fields to the users entity.

Pathauto will allow you to create aliases for the URL which is very nice for creating user friendly URL descriptions, but bear in mind that views contextual filters do not work with aliases well and cause cause you grief.

You will continue to learn about and pick up on other modules that meet certain needs, but I recommend you start conservative and master the few I have bolded in this answer first. Each of these modules is complex and will require study to master. As you encounter specific questions as \k them and you will probably get more useful answers.

Good Luck.


Hiding menu item depending on specific access I work on a D8 (8.6)
I want to hide some item on my menu depending on route param onto this link.

When I try to access the route I get a 403 error and works as expected but the the link inside the menu is still displayed.

I create a custom Accessinterface which return an AccessResult::allowed() or denied() depending on my rules.

Is there a core solution to prevent the link to be displayed on the main menu or I have to handle it in JS ?

My CustomAccessCheck :

class CustomAccessCheck implements AccessInterface
{

  public function access(AccountInterface $account)
  {
    $isAuthenticated = $account->isAuthenticated();

    try {
      $currentGroup = TestEntity::getInstance()->currentGroup;
    } catch (InvalidPluginDefinitionException $e) {
      return AccessResult::forbidden();
    }
    if ( $isAuthenticated &&
      ( !empty($currentGroup["id"]) && isset($currentGroup["IsActive"]) && $currentGroup["IsActive"])
    ) {
      return AccessResult::allowed();
    }
    return AccessResult::forbidden();
  }
}

I configure services and routing.yml in order to run this AccessChecker.
The custom menu contain some menu items which target the route configured.

My problem is even if the user don't have access to the route the menu item is displayed.

Thanks for help
Nico

I found by myself my mistake.

The menu items are always shown for super user.

The menu items are hidden/shown correctly for others users.


Error in simplenews when send the node more than one I am using module simplenews and when I send node more than one. Its show me this:-

  This newsletter has been sent.

Why and how can I solve this and don't want to show me again.

This is by design. Why would you want to send the same newsletter twice?
If you want to test your newsletter, choose the option "Send test newsletter". This can be done multiple times before sending out the newsletter to all subscribers.

EDIT: I just saw your other question (you should maybe combine both) and if you want to send a newsletter containing a View on a regular basis, see my answer to the other question or my documentation on drupal.org.


Pass hidden fields using drupalSettings to Twig template We have a paragraph field (field_pr_custom) on the Basic page content type that has a custom twig template, pr-custom.html.twig. In the twig template, we need to pass in an array inside of a <script> tag. To accomplish this, we use the mymodule_preprocess_paragraph__pr_custom hook and set the array using the #attached variable. However, when we print the drupalSettings we are not finding the value passed in. There is no Drupal behavior used.

How can we pass the value in an array from the mymodule_preprocess_paragraph__pr_custom into the drupalSettings variable inside the pr-custom.html.twig template?

Here is what we tried:

mymodule.module

function mymodule_preprocess_paragraph__pr_custom(&$variables) {
  // pass node id.
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node instanceof \Drupal\node\NodeInterface) {
    $variables['elements']['#attached']['drupalSettings']['myArray']['myvar'] = $node->id();
  }
}

pr-custom.html.twig

<div>
  {{ content.field_text }}
  <script>
    // this doesn't print myArray and doesn't even have it.
    console.log(drupalSettings);
  </script>
</div>

Wish I could comment...

Are you sure your hook is running?  the instanceof operator is not implemented correctly so you should be seeing an error when the hook tries to run.

Also, you may not need to add 'drupalSettings' to the 'elements' key.  You should be able to put it on the top level of $variables.


Form incorrectly displays differently depending on logged in user's role All logged in users can add a forum node. The current topic is determined by a field in another node (nid=77) and set to the default value for the node being created by this form.

While this all works perfectly for admin users, authenticated users see only '- Select a value -' as the default value. I verified with set_message that the code obtains the correct default value of the taxonomy term. What could be causing this? Note in case of authenticated user, <option value="_none"> is the only item in the select list. For admin user, the select list contains all of the taxonomy items with the correct option value set to selected="selected".

use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Form\FormStateInterface;

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

  if ($form_id != 'node_forum_form') {
    return FALSE;
  }
  else {

    $nid = 77; // Node ID 77 contains this week's topic in field_topic
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    $current_topic_id = $node->get('field_topic')->getString(); // get the TID
    $term = Term::load($current_topic_id); // load the term from the taxonomy
    $the_topic = $term->getName(); // get the Term Name for the debug message

    $form['field_topic']['widget']['#title'] = 'The Current Topic';
    $form['field_topic']['widget']['#default_value'] = $current_topic_id;
    $form['field_topic']['widget']['#disabled'] = TRUE;

    drupal_set_message('current_topic_id: ' . $current_topic_id . ', termName: ' .  $the_topic);

    return $form;
  }
}

For admin role, developer tools show <option value="44" selected="selected">Name of the entity</option> as well as all the other values/names of taxonomy items.

For authenticated user role, only one item is listed, <option value="_none" selected="selected">Select a value</option>.

Your code isn't manipulating the select field's options ($form['field_topic']['#options']), so the difference in options is something outside your code (you can confirm this by commenting out your form manipulation code).

If this is the case, you'll have to investigate why non-admin auth users are seeing empty options; it seems like it would have something to do with user permissions on your taxonomy, field, or something else that would prevent auth users from querying the valid terms for your taxonomy field.


How to close the overlay after form submission In order to be able to quickly edit Fullcalendar items, I altered the node edit form of the specific content type so the events are saved with AJAX and the page doesn't have to reload.

However, I don't know how to close the overlay afterwards. I found overlay_close_dialog(), but how do I implement this in my functions (I'm very new to Drupal coding)?

Until now I have:

<?php
/**
* Implements hook_form().
*/
function fullcalendar_ajax_node_save_form_alter(&$form, &$form_state, $form_id) {
  if( $form_id == 'agenda_item_node_form') {
     $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add to Apple Form'),
    '#weight' => 50,
      '#ajax' => array(
        'wrapper' => 'agenda-item-node-form',
        'callback' => 'fullcalendar_ajax_node_save_callback',
        'effect' => 'fade'
        ),
    '#submit' =>
      array (
        0 => 'node_form_submit',
      ),
    );
  }
  return $form;
}

function fullcalendar_ajax_node_save_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  return $form;
}
?>

The callback should be:

function fullcalendar_ajax_node_save_callback(&$form, &$form_state) {
  // Could check that the overlay is open? Part of core, so overkill
  if (module_exists('overlay') && overlay_get_mode() == 'child') {
     $current_path = current_path();
     overlay_close_dialog($current_path,
        array('query' => drupal_get_query_parameters(NULL, array('q', 'render'))));
    $form_state['redirect'] = FALSE;
  }
}

See overlay.module, about line 148 function overlay_init() for an example in core that uses as much drupal API as possible.


Override locale_block_view in custom module In the locale.module file there is:

function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

I would like to alter this function in my custom module. I've created a custom module named custom (module is enabled). I've tried to alter the function with this function : hook_block_view.

But when I do that it doesn't work:

function other_block_view($delta = '')
{
    die;
}

Nothing happens ... . The module works because hook_block_view_alter works. But I need to change the $links variable in that other function .. .

I've fixed it like this:

function theme_links__locale_block(&$variables) {
    $links = array();

    foreach($variables['links'] as $link)
    {
        $link['title'] = $link['language']->language;
        $links[] = $link;
    }

    $variables['links'] = $links;

    $content = theme_links($variables);
    return $content;
}


D7: Get terms from node and display other nodes with same term in block? I have a node that has terms:

Artist1

And need a block to show all the other nodes that has Artist1 as a term

I tried this solution Display the title of related nodes from taxonomy in block

I set it to "Provide a default argument", and configured that to use the nid of the node being viewed... and nothing

this seems simple but been working at it for hours now.

Try this module - https://drupal.org/project/views_arguments_extras
This allows you to select a field from the current node as a contextual filter.
Enable this module.
Create a  new view, block display, and the chose the relevant field as the contextual filter.
Configure the view as per your requirement and show the block on your node page. It should work.


use imce for images in articles but not within the editor By default, there's an imagefield of for the article and by default, in this imagefield you are only able to upload a file from your local disc.

Now i've installed imce and i can manage different folders with diffrent files but how do i connect the imagefield from the article to get one of those files from the folderstructure? To get the popup and click through the folderstructure and get the certain file?

You need the Filefield sources module. It allows you to select an existing file on the server.


Should all files be located publicly? Should all Drupal 8 files be located publicly, or should something like sites be the public document root?

[Michael@devserver drupal-8.1.1]$ ls -l
total 228
-rw-rw-r--.  1 Michael Michael    262 May  4 04:20 autoload.php
-rw-rw-r--.  1 Michael Michael   1437 May  4 04:20 composer.json
-rw-rw-r--.  1 Michael Michael 146226 May  4 04:20 composer.lock
drwxrwxr-x. 12 Michael Michael   4096 May  4 04:20 core
-rw-rw-r--.  1 Michael Michael   1272 May  4 04:20 example.gitignore
-rw-rw-r--.  1 Michael Michael    549 May  4 04:20 index.php
-rw-rw-r--.  1 Michael Michael  18092 Sep 23  2014 LICENSE.txt
drwxrwxr-x.  2 Michael Michael   4096 May  4 04:20 modules
drwxrwxr-x.  2 Michael Michael   4096 May  4 04:20 profiles
-rw-rw-r--.  1 Michael Michael   5889 May  4 04:20 README.txt
-rw-rw-r--.  1 Michael Michael   1596 May  4 04:20 robots.txt
drwxrwxr-x.  3 Michael Michael   4096 May  4 04:20 sites
drwxrwxr-x.  2 Michael Michael   4096 May  4 04:20 themes
-rw-rw-r--.  1 Michael Michael    554 May  4 04:20 update.php
drwxrwxr-x. 26 Michael Michael   4096 May  4 04:43 vendor
-rw-rw-r--.  1 Michael Michael   4006 May  4 04:20 web.config

The doc root should be where index.php is; that's where all requests for non-existent files are rewritten to.

If you mean "should the application and the front end be separate, like in other frameworks?", then yeah, maybe they should. But they're not at the moment, if memory serves there was a declined issue about doing just that when D8 was first being planned.


Override entity form handler I'm trying to alter an entity form handler. The method EntityType::setHandlerClass() allows for the 'form' handler to be set, but this value is an array, and I only want to override a single item of the array.

The entity handlers definition:

handlers = {
    "storage" = "Drupal\user\UserStorage",
    "storage_schema" = "Drupal\user\UserStorageSchema",
    "access" = "Drupal\user\UserAccessControlHandler",
    "list_builder" = "Drupal\user\UserListBuilder",
    "views_data" = "Drupal\user\UserViewsData",
    "route_provider" = {
      "html" = "Drupal\user\Entity\UserRouteProvider",
    },
    "form" = {
      "default" = "Drupal\user\ProfileForm",
      "cancel" = "Drupal\user\Form\UserCancelForm",
      "register" = "Drupal\user\RegisterForm"
    },
    "translation" = "Drupal\user\ProfileTranslationHandler"
  }

I'm trying to figure out how to override the form.register handler, but as the first argument to setEntityHandler() is a string, I cannot figure out how to set a nested value.

I have found the solution. Instead of using EntityType::setHandlerClass(), use EntityType::setFormClass().


Glossary option in Search API indexed nodes Does anyone know how to add glossary for search index nodes? In Views+Search API you dont get glossary option in contextual filters as you get in Views with content nodes.
Currently I am using grouped filter with each alphabet equal to title (trimmed to one character) but not very efficient way. Looking for a better approach.
Thanks.

To my knowledge the Search API does not support making a Glossary listing in a Contextual Filter. The best it can do is provide Facet Searching (after a search is performed).

Solr may support this using Shingles or something to help create the Glossary item, but no such Drupal submodule exists at the moment.


Including a file on every page in a module I have a module that provides about two dozen pages (in a site with 1000s of pages). I have a file that contains a number of large functions. I want to include this file on every page used by my module. My options appear to be:

Call module_load_include in every page callback - seems a slight pain
Add the file option to every item in hook_menu (which would be fine as long as I don't want the page callbacks to go in a separate files from my .module file)
Wrap all the functions in a class, include the file using files[] in my .info file and then call the functions like myclass::myfunction() [which sorta seems a slight misuse of the class system as most functions are returning arrays of data unconnected to each other]
Load the file in hook_init, which means it would be loaded for every page in my site, not just the dozen specialist pages

It looks like 3 may be the best bet, but I'm just wondering if I'm missing something that allows me to include the file in one place just for my module pages without lots of duplicate calls to module_load_include and without using classes.

If the file needs to be included on every page, the correct way is to use PHP's include or require, I don't think the fact that this is in a Drupal site should really make any difference.

I've seen plenty of modules that literally put the following at the top of the module file:

require_once('module.inc');
require_once('test.inc');

If you really want to do it  a 'Drupal' way, you can use module_load_include() (which just wraps around require_once internally), directly at the top of the file instead of inside your page callback. This is what I tend to do normally.

module_load_include('inc', 'MYMODULE', 'MYMODULE.something');

Adding the file in hook_init() is perfectly fine too, I can't think of any justification to use one over the other, it would be down to personal preference.


How do I show user created node in user profile page with edit mode? I have a content type 'child'. And I have give the permission to authenticated user to create child node. Its working fine.
But I need to show current user created node in user profile page with edit mode so user can easily updated own created node.
For this I have created views but I am not getting any option to show a created node as a edit form.

You have to give permission for Edit own page for that role to see "Edit link" in views or any other page.

Tha can be available from

www.example.com/people/permissions -> <Content Type>: Edit own content

You have to create a module for showing your custom link in user profile page

function <modulename>_menu() {
 $items['user/%user/<yourlink>'] = array(
    'title' => 'Your Pages',
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
 return $items;
}

Not to mention you have to clear cache after the this.


How to edit comment reply link for specific content type in Drupal 7 Is there a way I can programmatically edit comment reply links for a specific content type in Drupal 7?

So I need to check for the content type before changing the links:

<?php
if ($node->type == 'book') {
  // change comment reply links here
}
?>

Does anyone know how this can be achieved? Is there some sort of hook I need to implement?

You can try to use preprocess comment function:

function MYTHEME_preprocess_comment(&$vars) {
  unset($vars['content']['links']['comment']['#links']['comment-reply']);
}

Also check https://www.drupal.org/node/319298


Conditional email is not sent I have configured an email handler with the condition that an email message must be sent when a submission is updated by filling an image file field (the image file field has to be "filled"), but email message is not sent. The handler works if condition is removed

Core is 8.6.3 and Webform 8.x-5.0-rc26

Thanks

This issue has been fixed in the latest dev release of the Webform module.

https://www.drupal.org/project/webform/issues/3015020


Add Taxonomy Tags to uploaded images Is there any way to add the taxonomy term reference (tags) for each image uploaded? It just has 'alt tags' and title as default...

So far I can just add tags for a set of images (albums) but I want to be able to tag each of the images separately - one by one.

You can achieve your requirement by installing and configuring Taxonomy Image module.

  The taxonomy_image module allows site administrators to associate
  images with taxonomy terms. With the association created, an admin can
  then make a call to 'taxonomy_image_display()' from their theme or
  other PHP code to display the appropriate image.

Please follow this link as well.


How to display search results within the same Panels page I have front page with exposed filters and search results block on it within panels. In my case search results are displayed on a map. When i specify something in filters  and push "Search", i'm directed on search results page that has no panels and has path of front page's view. I want search results to stay within same panels as before i push "Search". How can i do it?

Do you use Content pane with Views? If so, under Pane settings make sure Use Panel path: Yes.


How to convert string count into number? How to convert string count into number? I have string count column in views i.e. by using the view aggregating I am counting the nodes of content, along with this I have field_number column i.e. from content type.

Now I want to subtracts these two column, while using math-expression its taking the string count column as string its not considering the count number.

Is there any solution to subtract these two fields?

Drupal doesn't provide any conversion of value in "Math Expression" field. So we need to fix it in another way, for example following these steps:

Add two new columns "string count" and  "field_number" same as previously added, excluding

When add fields tick "Exclude from display" checkbox
Select "Plain Text" to "Formatter" dropdown

After it, edit "Math-Expression" field, in "Expression" textarea write your mathematical expression with that newly added fields, e.g. [string_count_1] - [field_number_1]


How do I use dependency injection on \Drupal::moduleHandler() to a Controller? I am using the following line in a controller class.

    \Drupal::moduleHandler()->alter('mymodule_myfunction', $plugin_items);

Pareview.sh is giving me this error message.

  \Drupal calls should be avoided in classes, use dependency injection instead.

How should I accomplish this? Do I need to create a constructor, create a method, or a service? If so, what code should the service need? I found an example on "Drupal calls should be avoided in classes, use dependency injection instead" for a case where a service already exists.

In a controller you inject services by using the service container. For example ModuleHandler:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;

class MyController extends ControllerBase {

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Constructs a MyController object
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   */
  public function __construct(ModuleHandlerInterface $module_handler) {
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('module_handler')
    );
  }

Then you can avoid \Drupal calls by using the injected service:

$this->moduleHandler->alter('mymodule_myfunction', $plugin_items);

You can inject any service, existing ones from core/contrib or services you've defined in custom code in a *.services.yml file.

To find a core service name I usually look into core.services.yml, because that's the quickest way when you are working on a drupal project in your IDE.

You can use Drupal Console to list all services, not only from core:

drupal debug:container

You can also use the Devel module, which allows you to search for a name:

/devel/container/service


Where can I find the save destination path for a filefield? (via code) I have an image file field and I am attempting to write a little script that will programmatically scan my nodes and save images found in the body of my node into an image file field entitled field_post_image

I've been looking at the default process of what Drupal 7 + Image Field does and the example on SO found here: https://stackoverflow.com/questions/5129559/attaching-files-to-nodes-programmatically-in-drupal-7

I figured the best practice would be to save the images to the same folder as the file field destination in an effort to keep my /sites/default/files clean of orphaned files etc.

I've looked at both field_info_field and field_info_instance in the Field Info API and I can't seem to find the files destination (as configured in the Field UI)

Am I missing something and/or am I looking in the wrong place?

Thanks!

It's part of the instance settings of the file field, but it supports tokens. You want to call  file_field_widget_uri($field, $instance), that will give you a URI you can use to save the file.


How do I set a multilingual site name? I'm using a multiligual site in french,english and arabic and i want to set a custom sitename (or logo) for each one,for ex: if my sitename for english is : "one two three" i want it "un deux trois" for frensh version .
Is there anyway to fix that?
Thank you very much

i18n http://drupal.org/project/i18n provides "Multilingual variables"

As the site_name is a config variable, presumably it can be translated.

See also: http://drupal.org/node/313272

settings.php

/**
 * Multilingual settings
 *
 * This is a collection of variables that can be set up for each language when i18n is enabled.
 * These are the basic ones for Drupal core, but you can add your own here.
 */
$conf['i18n_variables'] = array(
  // Site name, slogan, mission, etc..
  'site_name',
  'site_slogan',
  'site_mission',
  'site_footer',
  // Different front page for each language
  'site_frontpage',
);


Remove features without lose functionality I'm working on a project where in the past was added a lot of features and was did in a way where right now a lot of them has a lot of circular dependencies and conflicts.

I want to start again, delete all the features, create new ones and avoid to each of them make conflicts with another.

My question is, how i can "remove" the features but not lose the changes to they did it on the project?, in other words how i can move the configuration "in code" into the database? for i able to remove the feature but preserve the configuration in the site?

I'm using Drupal 6

You can use the Features Tools Module to disable a features module while leaving the functionality that was provided by the feature in place.

Instructions provided by autopoietic here.

  First BACKUP YOUR DATABASE
  backup your feature (files) if you would like to use it again.
  Once installed, go to the 'recreate' page for a feature, uncheck all of the features
  components
  In order to save the elements to the DB you need to go to the admin/build/features/unlink
  page, check the element you need to import and submit.
  Now click on the 'Safe autocreate' button to recreate and replace the feature with an empty
  version.
  You can now disable the module without affecting your site configfuration.

These instructions note that "if you are using D6 there is an extra step" which I have added (step 4 above).


Replicating a page.tpl Region in Omega's structure I have a theme with a specific region and it is being printed using some PHP within the page.tpl.php file. It is also using a .js file and a .css file both within the PHP.

Here is the current code found within my old site's page.tpl.php file that allows for my region to show up:

<?php if (isset($page['sidepulltab'])) : ?>

            <?php print render($page['sidepulltab']);?>

<?php endif;?>

I have added to my subthemes .info file 3 lines (.js, .css and region):

scripts[] = js/stylepicker.js
stylesheets[all][] = css/stylepicker.css
regions[sidepulltab] = Side Pull Tab

I am not sure how to transfer this type of PHP region within Omega's Subtheme under the Appearance tab.

I tried adding the above code to page.tpl.php file which I copied into my subtheme from its original Alpha theme location. I do get my CSS and DIVs to show up, however my block region isn't printing inside.

Note: I'm using Omega 3, I have also cleared the cache. The region is showing up as "disabled" inside the Omega3 Apperence tab.

I have solved this issue.

I had to create a Zone. Then add the created Region to the new zone. I then created a zone--zonename.tpl.php file and within that i added

    <?php print $content; ?>

after that all content printed within this zone will be wrapped within my divs and .js and .css files will be applied.

Thank you 2pha for sticking in there with me and helping me with my overall brainstorming =-) hopefully this helps someone else messing around with this stuff.


How to delete Content Type created through features I was trying to use a project feature from openAid features based distribution.
So I copied all the features from that distribution and required contrib and custom modules in my drupal installation.

Then I enable the project feature from admin/structure/features which enables few other features like resources and partners.

Any how I was unable to make it work as per my requirement so I deleted all three folders including the features, contrib and custom modules.

but the issue is that it has created three content types Project, Partners and there is no option to delete them.

Please let me know if there is a way to delete those content types which were created through the features which I have already deleted.

Open the content type (for example: article) for editing which should bring you to a URL:

  admin/structure/types/manage/article

You can then append "/delete" into the URL like so:

  admin/structure/types/manage/article/delete

Which should open a form that will let you delete the content type. I don't know if this lets you delete ones that are coming from an active features package, but it definitely does help you delete obsolete content types from inactive features packages. So be careful

FYI, if you do this for multiple content types, don't open all the delete forms in multiple tabs and try to be clever by deleting several types at once. Bad things will happen :-p Make a backup and delete one content type at a time.


Adding a #suffix to a Drupal Product Form Payment Method Radio I have two radio buttons in my Drupal 7 product form. One for credit card and the other for 'send an invoice'. I'd like to add some text after each option but I don't know how.

In my hook_form_alter module this is what I'm attempting:

$form['commerce_payment']['payment_method']['#options']
['paypal_commerce_payment_paypal_wpp']['#suffix'] = 'text here';

However, this keeps throwing an error:

Warning: strlen() expects parameter 1 to be string, array given in
drupal_validate_utf8() (line 1599 of
/var/www/checkout/includes/bootstrap.inc).
Notice: Array to string conversion in format_string() (line 1550 of
/var/www/checkout/includes/bootstrap.inc).

And under the two radio options it just says 'Array' next to yet another radio button. Obviously not what I want. I want the text 'text here' to appear right after the 'Credit Card' radio option.

I also tried targeting the 'suffix' with '#field_suffix' to no avail.

Any idea how to make this happen?

The issue here could be the type of element $form['commerce_payment']['payment_method']['#options']['paypal_commerce_payment_paypal_wpp'] is.

Is paypal_commerce_payment_paypal_wpp the key of one your options?

Have you tried #description?


Form submission handler is not executed In a module, I am using the following code.

function mysimple_form($form, &$form_state) {
  $form['#method'] = 'get';
  $form['#action'] = '/buy/{_val_}';
  $form['search_location'] = array(
    '#type' => 'textfield',
    '#title' => 'Search',
    '#default_value' => t('kathmandu'),
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#attributes' => array(
      'placeholder' => t('Search')
    )
  );

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

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

function mysimple_form_submit($form, &$form_state) {
  krumo('asdsads');
  die();
}

I am using that form in hook_node_view().

function mymodule_node_view($node, $view_mode, $langcode) {
  $form = drupal_get_form('mysimple_form');
  $node->content['simpleform'] = array(
    '#weight' => -1,
    '#markup'=> drupal_render($form)
  );
}

The form is displayed perfectly, but the callback function doesn't seem to work.
I also tried $form['actions']['#submit][] = 'mysimple_form_submit'; and  $form['actions']['submit']['#submit][] = 'mysimple_form_submit'; but the form submission handler is still not invoked.

There is two problems:

You form method is GET so form submit action will be the actual path with the params like node/10?search_location=kathmandu&op=Search&form_build_id=form-s4JrAE91au_BWakeBLD7RUsktRTBXFCpJQrnHGiOjg8&form_token=ES2W0RDpLOnWZUsXOnP4f9gBmSXcYLvqhO9uy1ee4Vk&form_id=d7_exp_form
The second one you set your action to '/buy/{_val_}' so automatically after the submit you will redirect to /buy/{_val_} without invoke the submit handler.

Suggestion:

If you want to invoke the submit handler remove the $form['#method'] and $form['#action'], so your form will be with post method and your submit handler will invoked.
Remove only $form['#method'] and create menu entry /buy/% and you can do your submit handler logic in the /buy/% callback function.


How to properly alter response from Solr Search Module I'm working on Drupal Version 7.22 and I'm trying to modify the results coming from Solr using the hook provided by the Solr Search Module.

The specific hook can be found here: http://drupalcontrib.org/api/drupal/contributions!search_api_solr!search_api_solr.api.php/function/hook_search_api_solr_search_results_alter/7

Here's how I implemented it from the module:

/**
 * Implements hook_search_api_solr_search_results_alter().
 */
function zen_search_api_solr_search_results_alter(array &$results, SearchApiQueryInterface $query, Apache_Solr_Response $response){

  $locations = array();

  $rest = $results['results'];
  foreach($rest as $r){

    $place = $r['fields']['field_business_name'];
    $postal_code =  urlencode($r['fields']['field_business_address:postal_code']);

    $api = 'http://maps.googleapis.com/maps/api/geocode/json?address=' .  $postal_code . '&sensor=false';
    $api_results = file_get_contents($api);
        $data = json_decode($api_results, true);

        if($data['status'] == 'OK'){
            $location = $data['results'][0]['geometry']['location'];

            $locations[] = array(
                'place' => $place,
                'lat' => $location['lat'],
                'lng' => $location['lng']
            );
        }

  }

    $data = array('zen' => array('locations' => $locations));
    drupal_add_js($data, 'setting');

}

So basically what I'm trying to do here is to add the coordinates that I get from the Google  maps Geo-coding API using drupal_add_js.

But I'm getting the following error:

  Recoverable fatal error: Argument 3 passed to
  zen_search_api_solr_search_results_alter() must be an
  instance of Apache_Solr_Response, instance of stdClass given

Any ideas what's wrong here?

The problem was this one:

function zen_search_api_solr_search_results_alter(array &$results, SearchApiQueryInterface $query, Apache_Solr_Response $response){
  ...
}

It should be this:

function zen_search_api_solr_search_results_alter(&$results, $query, $response){
  ...
}


Is it possible to create a rule on the event "after saving an existing block"? The reason of such a rule would be that there is just one block a certain user can edit. And when he does so, after saving he is redirected to the blocks management page, which he has not the permission to see and manage. So I wish there would be a rule that allows to redirect "after saving an existing block" (combined with a condition of a certain user) to some other page.

I can't find any information about it in the documentation.

How is the user getting to the edit block screen? If its via contextual links then that should already be taking you can to the page you were on?

Or do you provide them the link to end the block? If so you could use the destination parameter to redirect then automatically (Same as what contextual links do) e.g.:

/admin/structure/block/manage/block/1/configure?destination=MYPAGETHEYSHOULDGOBACK


How to override twig templates I'm having a bit of a hard time with Drupal 8.

I've created a custom theme and am trying to override twig files. I've got debugging enabled so I know which files to copy to my template directory. However, when I copy a twig template it outputs nothing.

For example, I'm trying to wrap the site title in an H1 element. The core template file used in this case is /core/themes/stable/templates/block/block--system-branding-block.html.twig. If I add the H1 element in that file the header is inside a H1 element, but when I copy the twig file to my template directory the whole header is gone.

I can see in the source code that the file was found:

<!--  BEGIN OUTPUT from 'themes/mytheme/block--system-branding-block.html.twig' -->
<!--  END OUTPUT from 'themes/mytheme/block--system-branding-block.html.twig' -->

The documentation suggests that copying the relevant twig file is all that's needed but maybe I'm missing something? And if this should work, how can I debug this issue (the Apache error log doesn't report any errors).

Yes, to override twig file you just need to have the twig file with filename suggestion you get with debugger.

In case you are not able to see it, make sure of following:-

Your custom theme is enabled.
Folder where you kept your twig file has right permission.
Clear your Drupal caches.


How do I set a block title to the title of a referenced node? In Views 3, I have a block that is showing content from a particular Node ID. I'd like to have the title of that block set dynamically to what the referenced page's title is. I know this would be accomplished using Contextual Filters and that my display's title would be an argument, like %1 but I'm uncertain what the Contextual Filter settings should be. I'd rather not use PHP code if avoidable simply because I don't have the 'PHP Filter' module enabled on most sites I create.

Which settings should I use to make a block title the same as the title of a referenced node?

In Views, with a block output & Content Entity Relationship set up, in 'Contextual Filters':

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
- Override title (tick this & I used %1 with some text)

which offers "Override the view and other argument titles. Use "%1" for the first argument, "%2" for the second, etc."


Display a block based on current select option I have a select field that holds two options. When the second option is chosen, I want to display a block.

I know that with form API I should be able to do this. I'm just not sure on where to start. Any help getting me going would be greatly appreciated.

So far I have the code below.

function MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['account']['type'] = [
      '#title' => 'I am ordering for',
      '#type' => 'select',
      '#options' => [ 'Myself' => 'Myself', 'Someone' => 'Someone else' ],
      '#weight' => -100
      ];
}

Don't try to add the fields in a form alter hook. Do this in the field UI of the user entity /admin/config/people/accounts/fields. To change the visibility of fields dependending on the content of another field use

Conditional Fields

or the Form #states API directly, see How can I hide or show fields using states with hook form alter.

EDIT: The form #states api did the trick.


I am looking for suggestions on how to implement banner ads utilizing google type ads (or someone else) In order to help pay for our drupal 6 website we need to be able to derive some revenue from banner ads.  I am looking for suggestions on how to implement banner ads utilizing google type ads (or someone else) so that the ads display within a predefined rectangle and if the users clicks on an ad (which takes them to a new tab/page) it gives our company some revenue.

The most common ad network is Adsense. You will have to sign up for an account and then you can install the Adsense module which will manage your ads for you.

Beware however, this isn't a get rich quick type situation. Making money of Adsense requires a high volume of traffic.


Views getting wrong output? I am in little situation while creating D8 views. My scenario:

I have two Content Types:

Page, with fields:

title
teaser

Article, with fields:

name
reference_page (article have unlimited reference field for)

I want output in each ROW like:

title (from Page), teaser (from Page) and name of each Article where Page appears.

I am getting duplicate Page fields for each existence of page in Article.

Any suggestions?

Sounds like this may be solved by using aggregation

Change the No to Yes.


Get Node Author's Name in Custom Block In the admin area, to create a custom block, I go to:

Structure, Block layout, + Add custom block.

Once I create the custom block in the UI, I see a textarea field called "Body" where I can enter content.

How can I dynamically render the node author's name and profile picture in my custom block. I know I can type it in, but I would like to be able to insert some code (PHP, Twig or token) so that it pull's the author's name and profile image dynamically and prints it on the block. I do not want to use a views block, but a custom block instead.

One way to go about this is block preprocess function to retrieve the block's current node context & insert the relevant variables to be used by your Twig template. For example:

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function MYTHEME_preprocess_block(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  if (!is_null($node)) {
    $uid = $node->getOwnerId();
    $user = \Drupal\user\Entity\User::load($uid);
    if (!is_null($user)) {
      $username = $user->getDisplayName();
      $variables['$username'] = $username;
      // {{ username }} will be available within block.html.twig.
    }
  }
}


Add Class or ID to Menu Items Module: Popups
Site: http://www.mastersfunds.com.php5-23.dfw1-2.websitetestlink.com/images/slide1.jpg
Read Me: http://www.mastersfunds.com.php5-23.dfw1-2.websitetestlink.com/README.txt

Brief: I need to add a popup form to the menu links STAY INFORMED on the top-right and sidebar menu. I tried the Popups module, which loads all of my sites pages blank/white when activated. I am using it, but I am not sure how to use it.

The README.txt file has 4 ways of adding it, and I would like to use the second method (adding "popup" as CSS class to an existing link), but I am unable to add a custom CSS class/ID to a specific menu item. Is there a module that can do this, or does anyone know a easy way to setup?

I am pretty sure that the Menu Attributes module will work for you.  It adds several options to the menu entries, including ID and class attributes.  You would just need to edit the menu entries that you need this class on.


Why is Views ignoring nid as second argument? I create a view with two arguments: Taxonomy ID (tid) and Node NID (nid). I leave the default settings for tid and set a default argument for nid to a fixed value (let's say: 1). The tid argument is configured so that all values are shown in case it is not present. This should show all nodes except the one with NID 1.

BUT: This only works if the NID argument is the first argument. If it's the second argument, it is excluded from the query:

Query with nid as first argument:

SELECT node.nid AS nid
FROM node node
WHERE node.nid != 1  OR node.nid IS NULL

Query with nid as second argument:

SELECT node.nid AS nid
FROM node node

I'm wondering why that is? What I want to accomplish is actually to exclude the result of one view from another. To do that, I add nid as an argument, get the nids of a different view and tell views to exclude them. That works just fine, but only if nid is the first argument. But I need to have taxonomy as the first argument and I don't understand why that excludes my nid argument.

Although in a different context, I think I had the same problem here:
https://stackoverflow.com/questions/20248929/filter-a-drupal-view-displayed-in-a-panel-by-taxonomy-term-depending-on-domain

It seems that views ignores the second argument in case the first argument is not present, although the first argument is configured to show all values if it is not present. Setting the following PHP code as default argument for the taxonomy term solves my problem:

if (arg(0) != 'taxonomy') {
  return 'all';
} else {
  return arg(2);
}


Can a theme leverage block config Yaml files when installed for the first time? In my Drupal 8 contrib theme, when the theme is first enabled, a number of system blocks are dumped into the first region that's in my theme's info.yml file. From a UX perspective, this is not really desirable as it makes the theme look ungainly and off balance. The two core blocks in question are "Powered by Drupal" and the "Footer Menu" blocks.

I've played around with placing these two blocks where I want them (in my theme's case, the footer_first and footer_second regions), exporting the config for those and then placing the Yaml files in /mytheme/config/install. I then try a fresh Drupal 8 Beta 1 install on my local and activate the theme once again but the config files seem to have no effect. The two system blocks in question are yet again placed in the first region that's in my theme which is the top area.

I can fool Drupal by placing the footer regions first in my theme's info.yml file but this presents other issues - for example, when users view the block admin page and see those regions come up first when they are actually last.

My guess is, there is no good solution for this but I thought I would ask in case anyone had some ideas.

It turns out tim-plunkett was correct in his comment above. I used the config export function at /config/development/configuration/full/export to export all the block settings for my theme.

I then took all the generated YAML files and placed them in a new folder within my theme at /config/install. I then uninstalled the theme and then reinstalled it as the default. Voila, all my blocks, i.e., menu, help etc... were in their designated regions according to what had been exported in the YAML files.

Some examples of the file names are:

block.block.gratis_help.yml
block.block.gratis_main_menu.yml
block.block.gratis_branding.yml


Print preview and Printer-friendly version look different I am using a Print module with a bartik subtheme. I am trying to override the print module styles by using my theme's print.css file. Is this correc tway of doing this?

Both the print preview and preview via the printer-friendly version generated by the print module look different...

How would I go about overriding the print module styles?

This is how the print stylesheet is being called in my theme:
stylesheets[print][] = css/print.css

You have two separate stylesheets.

The 'preview' stylesheet needs to be configured in the CMS. You just enter into a field something like 'print.css' and create that file in your theme folder. This is nothing different than a typical stylesheet you would use anywhere else on the site.

The actual 'print' stylesheet (what you get when you press the print button) that you have declared in your .info file will style the resulting print.


Is it possible to assign permission to fields? The idea is that one can assign permission to fields just as node types. Evidently this gives great flexibility to webmasters to account for unforeseen requirements.

The advantage seems obvious: one can simply change permission of a particular field instead of defining a new node type and suffer the burden of migrating or re-creating old nodes into new ones. For example one can make an image field only visible to premium members.

I appreciate your hints about this.

Yeah,
You can make use of Field Permissions

  Features

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


How do I manually slide a carousel? I am using jCarousel as below:

jcarousel_add('#jcarousel',
  array('vertical' => false, 'scroll' => 3, 'horizontalDirection' => $direction, 'initCallback' => 'slCarousel_initCallback')
);

How can I manually slide the carousel?

When I run jQuery("#jcarousel").jcarousel().next();, in Firebug I get the following:

>>> jQuery("#jcarousel").jcarousel().next();
[]

I have tried this as well in the Firebug console:

var carousel = jQuery("#jcarousel").data('jcarousel');
//alert (carousel);
carousel.next();

I got the following:

>>> var carousel = jQuery("#jcarousel").data('jcarousel'); carousel.next()
TypeError: carousel is undefined

I fixed it by creating a global variable, and then assigning the value of the carousel to it.

var global_jc="";
function slCarousel_initCallback(carousel) {
  global_jc=carousel;
  // ...
}

Wherever I want to use next(), I use the following code:

global_jc.next();


In the File Entity module, what is the difference between "Manage display" and "Manage file display"? As per the screenshot, what is the difference between "Manage display" and "Manage file display"?

Manage display is the core page to manage the display of fields for various view modes.

The Manage file display tab is provided by the File Entity module; the page callback for that tab is file_entity_file_display_form(), whose description is:

  Form callback; presents file display settings for a given view mode.

So the difference is that display settings that relate to the file entity module have been separated out from the core Manage Display form, on a per view-mode basis, and that extra tab is where you set them.

As noted in the comments this is covered in a lot more detail as part of a broader question


Create taxonomy term with code I want to know how i can create taxonomy term programmatically.

I have this code

$term = new stdClass();
$term->name = ‘Term Name’;
$term->vid = 1; // ‘1’ is a vocabulary id you wish this term to assign to
$term->field_custom_field_name[LANGUAGE_NONE][0]['value'] = ‘Some value’; // OPTIONAL. If your term has a custom field attached it can added as simple as this
taxonomy_term_save($term); // Finally, save our term

From Link

I don't know where to write it. I think it will be in template.php with some hook ?

Drupal 7

If you just want to run an arbitrary PHP script through Drupal, the easiest way is probably using the Devel module

It provides a page (/devel/php) where you can copy/paste PHP code and have it run inside a fully bootstrapped instance of Drupal.


checkboxes on submit not showing correct values. Shows 0 always I am working with a form which contains list of checkboxes based on country. checkboxes are rendered correctly. But on submit, I don't get checkboxes' correct values. It always gets submitted as NOT CHECKED. My code is as below:

    foreach($fields as $id=>$title) {
          $form['test'.$code]['fields-'.$code] = array(
              '#type' => 'checkboxes',
              '#options' => drupal_map_assoc(array_keys($fields)),
              '#title' => t('Title'),
              '#attributes' => array('name' => 'field-'.$code.'-'.$id),
          );
        }

    function config_submit($form, &$form_state) {
      var_dump($form_state['values']);
      exit;
    }

outputs :

array (size=13)
  'fields-dk' =>
    array (size=7)
      'title' => int 0
      'reason' => int 0
      'doc-reference' => int 0
      'description' => int 0
      'upload-claim-file' => int 0
      'product-detail' => int 0
      'barcode-num' => int 0

Why is it returning always as 0? What am I missing?

While we can't see how your form is built completely, it might be that your custom attributes are affecting the element "name" in the form state.

i.e change

'#attributes' => array('name' => 'field-'.$code.'-'.$id),

to

'#attributes' => array('data-name' => 'field-'.$code.'-'.$id),


Invoke colorbox from a URL (not a link) All of the documentation assumes the content content load into colorbox will happen as a result of click... (e.g., the parameters calling colorbox are built into the link)

  My Example

I want to issue a redirect to a URL that then opens in colobox...

Any suggestions or experience solving this?

You should use java-script and the iframe support in color-box.

<script type="text/javascript">
  $(document).ready(function() {
    $("a", ".the-class-added-to-links-clicking-which-will-open-theurl-in-coloyxbox").click(
      function(event) {
        event.preventDefault();
        var elementURL = $(this).attr("href");
        $.colorbox({iframe: true, href: elementURL, innerWidth: 645, innerHeight: 509});
      });
  });
</script>

Code Source : https://stackoverflow.com/a/8933655/493742


how could the global $user be different between the Drupal interface and Services module? If i do:

hook_node_view($node, $view_mode, $langcode) {
        global $user;
        var_dump($user);
        die();
        // i get the correct dump of the current pre-authorized user
}

HOWEVER, if I dump global $user from one of my public Service endpoints an anonymous user. That dump comes from a GET service resource defined as:

'retrieve' => array(
       'help' => 'Retrieves a note',
       'file' => array('file' => 'inc', 'module' => 'noteresource'),
       'callback' => '_noteresource_retrieve',
       'access callback' => '_noteresource_access',
       'access arguments' => array('view'),
       'access arguments append' => TRUE,
       'args' => array(
         array(
           'name' => 'id',
           'type' => 'int',
           'description' => 'The id of the note to get',
           'source' => array('path' => '0'),
           'optional' => FALSE,
         )
       )
     )

How could that be?

For my Drupal configuration:
I am using LoginToboggan and Generate Password to handle registrations with only an email address. Alongside I am using the Services module which drives the API for our mobile app to tell the app if the user is logged in or not.

Under /admin/config/system/logintoboggan I have:

  I have "Set password" checked
  a "pre-authorize" permission selected for the "non-authenticated" role prior to email validation.
  I "never delete" unvalidated users
  I allow "immediate login" checked

Under /admin/config/people/accounts (regarding passwords), I have:

  Selected "Users may enter a password on registration. If left empty, a random password will be generated. This always applies when an administer is
  creating the account."
  Selected "Do not display" under generated password display.

The flow works well from the Drupal interface. That is, the registration is successful, the email is sent, and the user is logged immediately with the pre-authorize role applied even before validating their email. HOWEVER, my API endpoints still show that same user as anonymous users session when accessing it with global $user. I can literally reload the two pages as if there were no connection between them.

I have cleared all caches.
I have weight-ordered the roles with pre-authorzed 2nd, after anonymous and before authenticated user
I have verified the JS cookies are identical between the API page and Drupal interface  (see the side by side comparison in the screenshots below) and that the $_SESSION globals shows nothing pre-authorized or more.

Is there another way I should access the pre-authorized user other than global $user?

Nice question!
After reading your question.
you are not logged in to your app because you are sending the anonymous requests after login.
Workflow should be like this :
1)User register on the site.you will get the session id and session name.
2)Now need to set the session id and session name in headers then send the requests. you can check the same in drupal logs that whether your requests are coming from anonymous user or authenicated user.
if drupal getting the requests from anonymous user then make sure that headers are properly set. See the services module documentation to learn out about this.
Browser tools :

The Poster add-on for Firefox.
The REST Console app for Chrome.

if you are using the services module then take a look at its documentation


Batch API is setup in my module but it does not open batch window progress I am learning hot to use Drupal for my physics PHD. I was studying how to insert a batch into my custom module.
I wrote a simple module which allows to upload a CSV through a form, check the extension and save it into a directory. This is just a try because i want to use batch API for another custom module
Here is the code:

/**
* Implementation of hook_menu()
*/

function rhmtts_csvimport_menu() {
     $items['rhmtts/csvimport'] = array(
           'title' => 'Import CSV files',
           'page callback' => 'rhmtts_csvimport_page_default',
           'type' => MENU_NORMAL_ITEM,
           'access callback' => TRUE,
           );

     return $items;
}

function rhmtts_csvimport_uploadform() {
      $form['#attributes'] = array('enctype' => "multipart/form-data");
      $form['csvfile'] = array(
           '#type' => 'file',
           '#title' => t("Upload a CSV file"),
           '#size' => 40,
           );
      $form['submit'] = array(
           '#type' => 'submit',
           '#value' => t('Submit'),
           );
  return $form;
 }

           /////// Setup a batch //////////////

  function rhmtts_batch_submit(){

      $batch=array(
          'title' => t('Importing CSV ...'),
          'operations' => array(),
          'init_message' => t('Commencing'),
          'progress_message' => t('Processed @current out of @total.'),
          'error_message' => t('An error occurred during processing'),
          'finished' => 'rhmtts_csvimport_finished',
          );

      batch_set($batch);
      $batch['operations'][] = array('rhmtts_csvimport_uploadform_submit',                    array());

      }

     ////// Define finished function ////////////////////////////

   function rhmtts_csvimport_finished($success, $results, $operations) {

     if ($success) {
        $message = t('All users have had first and last names processed.');
      }
     else {
     $message = t('Finished with error.');
     }
   drupal_set_message($message);
   }

   ///// Methods definition ////

   function rhmtts_csvimport_uploadform_submit($form, &$form_state) {

   // create a csv upload directory in sites/default/files if it doesn't exist
   // yet
   $filepath = 'public://csvuploads';
   file_prepare_directory($filepath, FILE_CREATE_DIRECTORY);

   // save the uploaded file
   $file = file_save_upload('csvfile', array('file_validate_extensions' =>             array('CSV')), $filepath, FILE_EXISTS_REPLACE);
   drupal_set_message('The file you have uploaded is:
'.print_r($file,    TRUE).'
');

  // now read from it
  $realpath = drupal_realpath($file->uri);
  drupal_set_message("The real path of the file is $realpath");
  $fh = fopen($realpath, 'r');

  $table_header = NULL;
  $table = array();
  while(($row = fgetcsv($fh, NULL,';')) !== FALSE){
  if($table_header == NULL) {
  foreach($row as $field) {
    $table_header[] = $field;
    };
    continue;
    };
    $table_row = array();
    for($i = 0; $i < count($table_header) ; $i++) {
    $table_row[$table_header[$i]] = $row[$i];
    };
    $table[] = $table_row;
    }
    fclose($fh);
    drupal_set_message("You have uploaded:
".print_r($table, TRUE)."
");
   }

When i choose a file from the form it completed the operation, but the usual page showing batch progression is not showed. Is this because the operation is to fast? Or there are other problems in the code?

Many thanks

Alberto

your menu callback function is rhmtts_csvimport_page_default. This does not exist or currently does nothing.
Your form function rhmtts_csvimport_uploadform has this submit handler rhmtts_csvimport_uploadform_submit and it never calls or creates your batch function called rhmtts_batch_submit.

Your code is more or less all there I would:

use drupal_get_form as my hook_menu callback function and give it the name of my form function.
I would add my batch function onto the form submit handlers for my form as outlined here https://www.drupal.org/node/180528. Then it should all work.


WYSIWYG editor not displaying buttons and plugins I'm new to drupal and have not found an answer on SO yet.  I've updated to drupal 6.28, not ready to update to D7 yet, and the WYSIWYG and TinyMCE are not displaying.  Also I can't click/unclick checkboxes for buttons and plugins because I don't see checkboxes!  I also can't

Using TinyMCE 5.3.8. Other User Interface modules my site has are Superfish, jQuery plugins, IMCE Wysiwyg API bridge

Screenshots below.  Thanks!

http://imgur.com/UAZhxtZ

http://imgur.com/YX41wLF

Please look at your browser javascript console (native, Firebug, etc.), when the page with TinyMCE is loaded and post any error here (if there is no error, please reload the page). It will make possible to determine the cause of issue.


Preprocess a Paragraph when Added to Content Type I'm trying to disable a field in a Paragraph when it's added to a certain content type. Currently I'm using the following:

function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch($form_id) {
    case "node_content_type_form":
        $form['field_paragraph_content']['widget'][0]['subform']['field_paragraph_field']['#disabled'] = 'disabled';
      break;
  }
}

This works only after the node containing the paragraph has already been saved. When the paragraph in question is first added to the node the field_paragraph_field is not disabled.

How can I preprocess the Paragraph form when it is initially added to the content type so this field is always disabled?

If you want it to work when creating a node and when editing the node, you should make the change using both the node add form and the node edit form:

mymodule_form_node_content_type_form_alter()

mymodule_form_node_content_type_edit_form_alter()

Or in your hook_form_alter in the question:

case "node_content_type_form":
case "node_content_type_edit_form":

There's another way to do this using hook_field_widget_form_alter():

function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  if ($context['items']->getFieldDefinition()->getTargetBundle() == 'content_type' && $context['items']->getFieldDefinition()->getName() == 'field_paragraph_field') {
    $element['#disabled'] = TRUE;
  }

}


How to access the contents that are created by custom content type using module I am new to drupal, I wished to view the contents using custom modules. For that, I have created custom content type and added some contents. Now I want to create a module to display all the contents that are created by those content types, in a page. Contents should have title, image, description, date field. How can I do that.?

You can use Views to list content of custom content type.

Update(Programmatically load nodes):

<?php
$type = "custom_content_type";
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $node):
?>
<?php print $node->nid; ?>
<?php print $node->title; ?>
<?php endforeach; ?>

Ref: https://api.drupal.org/api/drupal/modules!node!node.module/function/node_load_multiple/7


Using form api to store google map location Is it possible to use form api (write codes) to display and store google map Latitude and Longitude? Most of the modules available is to add new google map field to drupal content type.
I don't want to use drupal content type to store as a node. i wish to store the location using db_insert.
Thanks

Yes, there are couple of ways of doing this. You would need to install Geofield which has a Form API element that can be used as such:

$form['location'] = array(
  '#type' => 'geofield_latlon',
  '#title' => t('Location'),
);

That'll give you a start to work from. I'm looking at embedding a clickable Google map using the GMap module as follows:

$form['contact_us']['map'] = array(
  '#description' => t('Enter your location to be displayed as a Google map.'),
  '#type' => 'gmap',
  '#title' => t('Location'),
  '#settings' => array(
    'zoom' => 8,
    'id' => 'location_map',
  ),
);

It shows the map however that is about all, so far. But it's another starting point for you!


Getting '#default_value' from $form I have this code:

$form['custom'] = array(
'#title' => t('Some title'),
'#type' => 'select',
'#options' => $custom,
'#default_value' => isset($option->name) ? $option->name_id : '',
'#description' => t('Some text goes here.'),

Now when i do print_r i get data from option and the name_id of the selected one.
No how can i get this data (name_id) from "#default_value" ??

In submit function i have this:

$custom=$form_state['values']['custom'];

But this only gets me the name not the name_id .

You can get it from the form itself:

$custom = $form['custom']['#default_value'];


Approach for doing Entity Relationships I'm looking for the best way to approach creating relationships using Drupal 7.  I am looking for advice on creating the following:

1) A "letter" content type (as in an old fashioned letter)
  a) From Person (i.e. "John Doe")
  b) Associated From address ("12348 Street")
  c) To Person
  d) Associated To address
  e) Postage Date
  f) File attachment of scanned letter

2) A person can have one or more addresses (I am recording some family history of letters sent and people have changed addresses over time)

3) Ability to select the Person/Address in the Letter content type for the From / To Person.

I've been reading the documentation, but I'm just unclear on the best approach.  Would appreciate suggestions. For example, I started out creating a field for From Name and To Name and From Address and To Address, but realized I'd be creating a lot of redundant data and that it would be better to create relationships, but am not sure how to accomplish that.  Should I create a Person Content type?  If not explicit instructions, would appreciate a general point in the right direction.

Just general ideas, not a solution...

I would check out the entity reference module (https://drupal.org/project/entityreference) as a starting point, to get an idea of how it works, so you can plan your project with this in mind. Entity reference makes it easy to link one entity to another, then build views to generate lists of related items. Entity views attachment (EVA, https://drupal.org/project/eva) can help you attach views of related items to entities. (i.e. you could display a list of letters as a view attached to a person)

You may also want to check out the addressfield module (https://drupal.org/project/addressfield) especially if you have international addresses to work with. It's a little tweaky, since it handles the entire address as a single field, but it saves you the trouble of implementing several fields to catpture each address.

From your description, it seems like you would want at least these content types: letter, person, address (or place). But it's hard to say for sure without knowing your complete vision.