Hide/disable EDIT & DELETE links in menu-customize form How to hide/disable EDIT & DELETE links in menu-customize form.

www.yoursite.com/admin/build/menu-customize/primary-links

I think that those links bring more potential problems than benefits. It would be great if anyone knew how to disable them per role but a global disable is fine too. I'm using Drupal 6.

p.s. I still want user to have permission to rearrange menu items ordering.

Thanks for the help.

You can create a small custom module and implement hook_form_FORM_ID_alter().  Below is a quick example for Drupal 6:

.module file

<?php
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function YOURMODULE_form_menu_overview_form_alter(&$form, &$form_state) {
  GLOBAL $user;

  // Check if user has a certain role or not and menu is primary links
  // Change ROLEID to the role id you want operations hidden from
  if (!array_key_exists(ROLEID, $user->roles) && arg(3) == 'primary-links') {

    // Hide edit/delete menu operations
    foreach ($form as $key => $ele) {
      if (substr($key, 0, 5) == 'mlid:') {
        unset($form[$key]['operations']);
      }
    }

  }
}

Change YOURMODULE to the name of the module you are creating.  For assistance creating custom modules, see the Module developer's guide.

To work in Drupal 7, I believe all you would need to do is change arg(3) to arg(4) due to the path changes.


Filtering view by content author OR referenced field I have a user that is author and is referenced on a certain content type, I want to be able to filter a view to show all nodes where the user is referenced, example field_user and where the user is the author.

I can have access to the current user from my view and I did had a group with the OR operator so it can be filter to content author and from referenced field.

When I do things separately both work, I mean, I can get the nodes where the user is author and then I can get the nodes where he is referenced but when I add the two filters simultaneously with the OR operand this does not work, any idea?

In the image below are my settings to the view, I think that you may understand what I am doing.

Thank you.

As no one answered and I couldn't find a way to solve this trhough UI, I used views_pre_render hook to solve my problem.

You can see the solution I found here.


Implement hook_field_create_instance(), hook_field_delete_instance() and hook_field_attach_rename_bundle() When creating a new field type (e.g. address or dimension), I am looking for the Drupal 8 equivalent of hook_field_create_instance() and hook_field_delete_instance() that are available in Drupal 7.
The same goes for hook_field_attach_rename_bundle().

The hook_field_create_instance() could be used e.g. for defining default values on existing entities. Let's say define the new field default value on existing Node instances after attaching (= creating a field instance) to a Content Type.

After digging around on the parent classes and interfaces of the classes that are involved in the definition of a new field type (FieldFormatter, FieldType, FieldWidget namespaces) + Field Types API, I found the PluginManagerBase::createInstance (and thus FieldTypePluginManager::createInstance) but didn't found a way to define custom code for these operations.

These two drupal resources should get you there:

https://www.drupal.org/node/2054619
https://www.drupal.org/node/2012896

As an aside, here is how I found the changes: Drupal Changes


How to set date format in drupal 8 for date time field? The default date format of drupal 8 is d.m.Y but I want it to be d-M-Y.

I have tried

#format => 'd-m-Y'

#date_format => 'd-m-Y'

My date field

$form['start_date'] = [
           '#type' => 'datetime',
           '#title' => t('Start Date'),
           '#date_format' => 'd-m-Y',
           '#description' => date($date_format, time()),
           '#default_value' => time()
         ];

But none of them worked.

In Drupal 8, the date format and time format are separated. The values for this has to be set separately.

I found this by creating new cck field in a content type and printing it from form alter.

$date_format = 'Y-m-d'; $time_format = 'H:i';

$form['start_date'] = [
      '#type' => 'datetime',
      '#title' => t('Start Date'),
      '#date_date_format' => $date_format,
      '#date_time_format' => $time_format,
      '#description' => date($date_format, time()),
      '#default_value' => Drupal\Core\Datetime\DrupalDateTime::createFromTimestamp(time())
    ];


Displaying a single result out of three results I have a view block that is set up to produce three product titles sorted from a taxonomy term (flowers). I have a view whose machine name is latest_products.
In a preprocess function I use the following code.
$variables['views_twig_var'] = views_embed_view('latest_products','block_1');

In a template, I use {{ views_twig_var }}, which produces all three titles on the page.
If it's possible, how would I use it in the template file to only show the first result?
{{ views_twig_var[0] }} doesn't work.
I would then use the second result further down the page, with the final result even further down.
For now, I created it in three different blocks, with each block producing a single result, but for my curiosity and for future reference I am wondering if there is a faster way.

you can do it without preprocess, by using the Twig Tweak module, it gives you the possibility to render your view in twig with display filters and so on like the following:
{{ drupal_view_result('latest_products', 'block_1') }}

The drupal_view_result give you the array of result so you can get the first result with:
{{ drupal_view_result('latest_products', 'block_1')[0] }}

of type ResultRow and then get the entity with:
{{ drupal_view_result('latest_products', 'block_1')[0]._entity }}

For more information see the module Cheat sheet page


Getting URL alias of a term I am writing a module, and am confused about the term's URLs. because, if pathauto moduel is installed, then the alias of that module should be provided. How to achieve this?

Default drupal's URL: taxonomy/term/30
Pathauto's probable pattern:

category/30
category/[title]
category/[title]/[id]
...and millions of other possible patte

Using drupal_get_path_alias() returns drupal's default path.

How should I get the path used by pathauto? I have seen pathauto's module,
but it does not provide an API for this purpose as it seems.

Just use the url() function. It will return aliased path if you have pathauto installed.

Example:

$link = url('taxonomy/term/1');


Security considerations for special characters in usernames? I would like to create some users on a Drupal site where the usernames are actually company names and some of those company names contain ampersands or other non-alphanumeric characters.

I have read this answer which describes how that might be achieved (by overriding the form validation for creating/editing a user).

My question is: Would there be some security risk in allowing special characters such as &/#?()+ in usernames, or did the Drupal developers make these characters illegal purely for aesthetic reasons?

I can think of three concerns when it comes to usernames and security: Cross Site Scripting (XSS), SQL Injection, and Homograph "attacks".

As long as you don't allow the < and > in usernames then you don't have to worry about XSS. If you want to allow one or both of those then you need to be more suspicious and do a thorough test of your site for XSS by entering a malicious username and seeing what happens.

SQL Injection should not be a problem. This has largely been solved in Drupal for a while and DBTNG in Drupal 7 makes it even less common. You could still test for it with some weird usernames that contain '; and other character combinations.

Homograph is then the worst thing. For a while (maybe still) you could register a username like Admin which looks a lot like Admin but in fact uses the MATHEMATICAL BOLD CAPITAL A from the list of confusables. The problem would arise from someone using a username that is a homographic match to a known "admin" on your site to register on the site and then using the contact or private message feature of the site (or even a public node/comment) to trick other users of the site into doing something stupid (e.g. posting a message "Our site is having login problems, please go to http://sitename.evil.example/password-reset and enter your credentials to have your login fixed."). By adding more characters to the allowed set of username characters you make a homograph social-engineering attack more likely/easier. I don't consider this to be a big problem and you should consider whether this is really a problem for your site before worrying about it.

The Real Name module is meant to give you this ability without the form alter. I don't think it's really any safer for homograph attacks, though.


Logging into Drupal from a non-Drupal site I would like to create an interface on a non-Drupal site that will allow me to login to my Drupal site?

How can I accomplish this, either with custom code or with an existing Drupal module?

Use Token authentication

Token Authentication provides a token for use in the URL to authenticate users to your site. It only works on paths configured in the settings page.
Originally this module was intended to offer simple authentication for RSS feeds to allow feed readers to pull customized content listings. You can now use it to provide a simple browsing experience of any Drupal content.

You would need to code a bit behind the scene - namely inject new token to proper table on successful off-site login, but it should be possible.
But maybe for your case opposite approach would be better? You can add custom submit handler to Drupal's login form to get arbitrary PHP code executed.


View in a list Machine Names I am new to Drupal7, and working on a site with different users.

And my probably I am currently encountering is when whenever someone creates a content, field, etc. It generates a machine name.

Using Drupal, it automatically generates one based on the given title of node.
But it won't be saved if the machine name already exist.

Is there anyway to know what machine names exist? And to which this machine name is assigned?

For some "object" there is.

on admin/reports/fields you find a list of every field, with type and machine name
on admin/structure/types you find a list of every content type, wth machine name

and so on for views, rules and any other "object".

If you need a "report" you could use Views, o make a directly a query.


Advanced Forum Error When Posting I have updated today to the latest version of Advanced Forum and when trying to post a new topic got the following error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '329-node' for key 'PRIMARY': INSERT INTO {ip_posts} (type, id, ip) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 329 [:db_insert_placeholder_2] => 38932973 ) in ip_posts_insert() (line 162 of /home/thanatos/public_html/sites/all/modules/ip-7.x-1.4/ip/ip.module).

Could this be related to php timeout? I'm asking this because I took quite a while typing the Topic before posting it, because I was working it in HTML in Dreamweaver. However when I went back and created a new topic and posted it instantly, I had no issues.

Thanks in advance.

Miguel

The error has nothing to do with the Advanced Forum module, the error is coming from the IP address manager module. From it's error message, it looks like it's trying to insert a record that already exists. It could be a problem with how you upgraded that module (your dir suggests its version 1.4, but the line number matches the latest 2.0-beta) or it could be a bug.

Either way, if you're not concerned with preserving historical data in the module, uninstalling, removing, and reinstalling the IP address manager module would be one way to get rid of the error.


Job board: Faceted Search with "OR" operator, but sort results by most matching facet criterias/term count I'm quite stuck with searching for a solution for my problem and I hope that you can maybe help me.

In general I want to build a small job platform. It includes an "Explore"-Section, which is just like a Search-Page with Facets.
The actual job-nodes can be tagged with terms of the two vocabulary "skills" and "interests".
The facets on the search page allow the user to filter jobs exactly along these skills and interests.
However, I want to use the "OR"-Operator for the Facets, so that the user gets a list with jobs, that nearly perfect match their skills & interest but also jobs that match only some of these terms.

So, here you can see the default listing page. On the left are the Facets for interest and type (Operator "OR"). On the right, you can see the result set with title, and the node's skills & interest terms:
Jobsearch Default page

Now, I'm applying "Musik" and "Kultur" as interest-filters:
Jobsearch with applied filters

As you can see in the result-set, the OR-operator delivers all the results.
However, I would like to sort these results according to their "relevance" resp. according to the count of matched criterias.
The 4. and 5. results match both terms, that are selected in the facet, but they should be listed in front of all other terms.

So, I hope you understand what I want to achieve. I started at first with Views to accomplish the goal, but I then switched to search_api and SOLR as I think, that this approach is more enhanceable in the future.

The second aim is, that a user can store his/her individual interests & skills (the filters mentioned before) in his user profile. Here, the user should see individual job recommendations based on his profile on his account-page.

So, any hints, tips, tricks, links are very welcome as I have no idea if I'm on the right track to solve my problem(s). :)

Robert

Maybe this approach could be an alternative:
Instead of using the tags as facets/filters, I could use them just as search input.
when i'm typing my terms/tags within the search field of an apache-sold-search-page, i'm getting exactly the results sorted by their relevance:

Searching for filters/term instead of using them as real filters

So, maybe I have just to do a small piece of code, that automatically creates a search query based on the clicked term/tags…


Load nodes from specific content type Thanks to kiamlaluno♦ I can load recent nodes using node_load() but how can I load recent nodes from a specific content type?

You should always enclose the table names with curly brackets. That way table prefix (if any) will be added automatically. It's better to use that way all the time.

This is how your query should look like:

SELECT nid FROM {node} WHERE type = 'page' ORDER BY created DESC.


Drupal View Deleted by mistake So this is my problem. I deleted a view for my drupal 5 site and have no idea to recreate it. I've tried to recreated the view but it's not the same what so ever. The view I deleted was for a video page. It displayed videos, from third-party sites. The view displayed the title and a thumbnail of the the embedded video. The view that I recreated only displays the video link and not the thumbnail too. I've tried altering the fields to display the thumbnails. But with no luck. Any Ideas?

There is no built-in way to restore a deleted view. Check if you have an old database dump somewhere (a regular backup, or maybe you created one when you put your site live). Depending on your hosting setup, your webhost may also have created backups of your server.

If that all fails, I'm afraid you will need to rebuild your view manually. While you're at it, consider upgrading your site to Drupal 7. Newer versions of Views make it really easy to export your view to code, so you can store your view in a version control system and never lose it again.


How can I hide and print a field in my tpl.php? I'm using kickstart 2. I have product variation types and a content type for each product. field_desc under the content type manage fields, I have managed to hide and print render successfully in my node--product--type.tpl.php.

However, I have another field called field_spec which is a variation type field rather than a content type field. when I use the following codes in my tpl.php to hide and print the field_spec, this field is not hidden or printed where I want.

I use the following codes to hide and print both field_spec and field_desc however field_spec isn't hiding whereas field_desc is:

  <?php
    hide($content['field_desc']);
  ?>

 <?php
 print render($content['field_desc']);
 ?>

I have checked that field_spec is spelled correctly, I have cleared caches etc. however I cannot hide and print field_spec.

Is this something to do with the fact field_desc is a content type field whereas field_spec is a variation type field?

Thank you

I think you need to use $content['product:field_NAME'] for this

See this answer for more info: Print out a Drupal Commerce field only if it has a value


how to cache my site background image? I am using an image as my site background that is of size 2.7MB. Because of its image size alone it takes 7+ seconds for the page to load.

Question: Can/How do I cache this background image at user's browser caches that it is not downloaded every single time?

Basically, i understand that first load will be slow but if cached - subsequent loads would be faster then.

The default drupal .htaccess settings should have your browser cache this image for 2 weeks. If this is not working I recommend installing the mod_expires module & the mod_headers module on your server. If 2 weeks is not long enough, you will need to modify your .htaccess file to set the expires & cache control headers for this file. An example of that below:

<FilesMatch "my-big-image\.jpg$">
  <IfModule mod_expires.c>
    # Enable expiration.
    ExpiresActive On

    # Cache this file for 1 year after access (A).
    ExpiresDefault A31556926
  </IfModule>
  <IfModule mod_headers.c>
    # Make this file publicly cacheable.
    Header append Cache-Control "public"
  </IfModule>
</FilesMatch>

At a bare minimum, you can try adding this line to the bottom of your .htaccess file. This doesn't require any apache modules to be installed and it should have your sever send back a small 304 instead of a large 200.

FileETag MTime Size


How can I tell if a node has more than one parent taxonomy term assigned to it I have a situation where the colour scheme of a node depends upon which taxonomy terms have been assigned to it.

However, if a node has more than 1 parent taxonomy term assigned to it, this is a certain colour scheme of itself. I'm not sure of the technical name but by parent taxonomy term I mean the top level taxonomy term, as there will only ever be 2 levels deep, so I call this parent taxononomy term.

So I need a certain html class to be created for these special nodes who have more than one taxonomy term assigned to them.

I was thinking even to use a hidden field and to write a module which checks how many parent taxonomy terms have been assigned before creating or saving this content type in question, and then simply adds a value to this hidden field, I could then use this field to add a class to my content in views.

Am I allowed to ask for suggestions here for this, I am sorry if this is against rules

There's no need to store this information when it can be calculated on the fly.

The taxonomy module contains a function called taxonomy_get_parents() that can retrieve the parents for a given term. Using this, you can iterate over the node field values to look for any root ("parent") level  terms (i.e. they have no parent) and count the number of terms accordingly.

// Given a node object & taxonomy field machine name, return count of root terms
function mymodule_node_root_term_count($node, $field_name) {
  $count = 0;

  // $node->{$field_name}[LANGUAGE_NONE] will vary with multi-lingual enviroment
  foreach($node->{$field_name}[LANGUAGE_NONE] as $term) {
    $parents = taxonomy_get_parents($term['tid']);
    // A root term will return an empty array.
    $count += empty($parents) ? 1 : 0;
  }

  return $count;
}

Once you've built your logic for determining the type of node, you can utilize it in a theme preprocess function to add CSS classes accordingly.


Migrate class not registering properly I am having trouble creating and registering migrate modules. At the moment, when I go to the UI screen, it says 'Class X no longer exists' (so, at least its being picked up) and wont show in the list of migrations on  the page. At the moment, I have only implemented one class and had this issue (when I figure this out, I will create everything else). Here is my code:

function migrate_rcmd_migrate_api() {
  $api = array(
    'api' => 2,
    'groups' => array(
      'Test' => array(
        'title' => t('Test Migrations'),
      ),
    ),
    'migrations' => array(
      'EventNode' => array(
        'class_name' => 'EventNodeMigration',
        'group_name' => 'Test',
      ),
      'CareerNode' => array(
        'class_name' => 'CareerNodeMigration',
        'group_name' => 'Test',
      ),
      'NodeRegistrationEntity' => array(
        'class_name' => 'NodeRegistrationEntityMigration',
        'group_name' => 'Test',
      ),
      'JobPostingEntity' => array(
        'class_name' => 'JobPostingEntityMigration',
        'group_name' => 'Test',
      ),
      'CoverLetterFileEntity' =>array(  //may only need one file entity migration class
        'class_name' => 'CoverLetterFileEntityMigration',
        'group_name' => 'Test',
      ),
      'ResumeFileEntity' => array(
        'class_name' => 'ResumeFileEntityMigration',
        'group_name' => 'Test',
      ),
    ),
  );
  return $api;
}

and

abstract class Test_Migration extends DynamicMigration {
  public function __construct() {
    // Always call the parent constructor first for basic setup
    parent::__construct();

    // With migrate_ui enabled, migration pages will indicate people involved in
    // the particular migration, with their role and contact info. We default the
    // list in the shared class; it can be overridden for specific migrations.
    $this->team = array(
      new MigrateTeamMember('Liz Taster', 'ltaster@example.com', t('Product Owner')),
      new MigrateTeamMember('Larry Brewer', 'lbrewer@example.com', t('Implementor')),
    );

    // Individual mappings in a migration can be linked to a ticket or issue
    // in an external tracking system. Define the URL pattern here in the shared
    // class with ':id:' representing the position of the issue number, then add
    // ->issueNumber(1234) to a mapping.
    $this->issuePattern = 'http://drupal.org/node/:id:';
  }
}

class EventNodeMigration extends Test_Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    //WE WILL NEED THIS
    //$this->dependencies = array('BeerTerm', 'BeerUser');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'nid' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'The primary identifier for a node.',
          'alias' => 'n',
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );
    //example
    $query = Database::getConnection('default', 'legacy')
             ->select('node', 'n')
             ->fields('n', array('nid','vid','type','language','title','uid','status','created', 'changed','comment','promote','sticky','tnid','translate','uuid'))
              ->condition('type', 'events','=');
              //ADD JOINS TO FIELD TABLES HERE
    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationNode('events');

    $this->addSimpleMappings(array('nid','vid','type','language','title','uid','status','created', 'changed','comment','promote','sticky','tnid','translate','uuid'));
    //$this->addFieldMapping('title', 'page_title');
    //$this->addFieldMapping('body', 'page_body');
  }
}

Be sure:

your migrate_rcmd_migrate_api function is in the file migrate_rcmd.migrate.inc.
your Classes are included in .inc files defined in your modules .info file. See this documentation page on Migrate: https://drupal.org/node/1006982
Lastly in Migrate > 2.5 (i think thats the right version) migration auto discovery is now gone. You can use drush migrate-register to register your migrations and classes. See drush help migrate-register as needed.
when in doubt clear your caches: drush cc all to be sure the .inc files are registered in drupals code registry.


What is the risk of using number in image style preset name (imagecache in D6) There is a message below the preset name to be written. It not suggest us to write number:

The name is used in URLs for generated images. Use only lowercase alphanumeric characters, underscores (_), and hyphens (-).

Sometime I need the name with number such as thumb90, profile100x150, etc.

I can see some developer also write number in the name field.

Even no problem so far, I need to know what actually the risk of using number together in the name.

I have never seen the term "alphanumeric" refer to anything other than a combination of letters and numbers.

Since the style name gets used in the URL, the restriction to "Use only lowercase alphanumeric characters, underscores (_), and hyphens (-)" likely has to do with avoiding any escaping issues with URLs and for portability across filesystems that may not support the full range of characters in filepaths.

Personally, I have never (nor have my clients) run into any issues with using numbers in image sytles, though as a best practice I lean towards using descriptive names for use, rather than size, in the sytle name.  So, I will try to use "thumbnail_square" instead of "thumbnail_90x90", in case I end up changing the size at some point.


How to link up a view created page using hook_menu I have created a page using view and defined a path for the view. I want to add a tab using MENU_LOCAL_TASK from hook_menu() How can I add a link to the view for the page callback?

EDIT

I have tried this but does not work.

$items['user/%/my-fees'] = array(
        'title' => 'My Fees',
        'description' => 'Student Payment Schedule ',
        'page callback' => 'views_embed_view',
        'page arguments' => array('payment_schedules', 'user_fees', 1),
        'type' => MENU_LOCAL_TASK,
    );

hook_menu() is not required. We can set the tab, or link, in the view itself under page settings -> Menu.

I have used the menu options of the view to add the item in my user navigation.


How can I return the selected radio button text on a form I have two radio buttons on a form for example as below:

() Paul

() James

When I use the follwoing code, I am getting the values 0 or 1 depending on my selection. How can I get Paul or James?
Thanks for your help.

$chosen =$form_state['values']['name_options'];

If the value you want is not in $form_state you can check in the $form parameter for the original form definition.

e.g:

$chosen = $form['name_options']['#options'][$form_state['values']['name_options']];


Using an aggregated entity query to find duplicate taxonomy terms Due to a content migration bug, there are nodes in our site that reference the same taxonomy term multiple times with different deltas:

bundle  deleted entity_id   revision_id langcode    delta   field_term_target_id
article 0   1061    1062    en  0   307
article 0   1061    1062    en  1   307

I can find these with the following database query

SELECT
    entity_id, field_term_target_id, COUNT(*) as count
FROM node__field_industries
GROUP BY entity_id, field_industries_target_id
HAVING count > 1;

For building a tool that lists these nodes within Drupal, I would like to use an entity query instead of accessing the database directly.

I've tried the following:

\Drupal::entityTypeManager()
  ->getStorage('node')
  ->getAggregateQuery()
  ->groupBy('nid')
  ->groupBy('field_industries')
  ->aggregate('field_industries.delta', 'COUNT')
  ->conditionAggregate('field_industries.delta', 'COUNT', 1, '>')
  ->execute();

But this results in an error Invalid specifier 'delta'. If I aggregate on 'field_industries' instead (which seems wrong, as I'm already grouping on that value), I get completely wrong results back (specifically, vastly inflated values for COUNT, which can be as high as 16 even for nodes that are not affected by the bug).

So I guess my question is: How do I aggregate on a non-default column in the field table (such as the delta column)?

You can use the Database abstraction layer:

$connection = Drupal::database();
$query = $connection->select('node__field_industries', 'i');
$query->fields('i', ['entity_id', 'field_term_target_id']);
$query->addExpression('COUNT(*)', 'count');
$query->groupBy('i.entity_id');
$query->groupBy('i.field_term_target_id');
$query->having('COUNT(*) > 1');

$results = $query->execute()->fetchAll();

Hope this helps


How to suppress composer autoload when installed as an unused dependecy? I'm running a D7 site with the composer module installed as an unused dependency of the OpenLayers Module. The issue I'm having is that my watch dog log is filled with RuntimeException: Autoloader not found: /var/www/html/phisigmarho.org/sites/all/vendor/autoload.php in composer_manager_register_autoloader() (line 173 of /var/www/html/phisigmarho.org/sites/all/modules/composer_manager/composer_manager.module). and has caused at least one  /home/phislub9/public_html/error_log [24-Feb-2017 09:57:30 America/New_York] PHP Fatal error: Class ‘SensioLabs\Security\SecurityChecker’ not found in /home/phislub9/public_html/sites/all/modules/composer_manager/composer_manager_sa/composer_manager_sa.module on line 83

Part of my issue is that the site is on a shared server that I don't think I can install composer on, so I'm kind of stuck letting the errors build up. I didn't think it was a problem till hitting the fatal error, and it's bad practice to let the script run and take up server resources. So is there some way to work around this? I don't use composer for anything, so I would happily get rid of it but it's a dependency. Can a dependent unused module be suppressed in some way?

I doubt composer manager is an unused dependency. It would make very little sense to list that module as a dependency and not using it. Are you sure there are no packages listed on yoursite.com/admin/config/system/composer-manager?

It is very likely that the module that defines the dependency requires some composer packages to function properly. Even if you managed to suppress the composer manager module, the main module would not have access to the package that composer was supposed to fetch, and likely will not work as expected. In that case you should consider two things:

Move to a host that gives you more privileges
Download the site to your own computer, install and run composer in the file directory configured on /admin/config/system/composer-manager/settings and re-upload the entire site, including the vendor directory.

If there are really really really no packages, you could try to change composer manager's status in the database system table to 0. That disabled the module without checking for dependencies. It could however break a lot of other things, so have your backups and proceed with caution.


substr plugin not working I have been using Migrate API as a means to pull in RSS Data as nodes. Currently in Drupal 8 it doesn't seem there is any other reasonable way to do this.

One of my fields is a link that ends in a series of 6 numbers. I need those numbers as an id to go into the url. The substr plugin seems like it would be perfectly suited to accomplish this, but doesn't seem to work at all.

What I have in my YAML file :

grantid:
-
  plugin: substr
  source: guid
    start: 61
    length: 6

The error in my drush window when I attempt to even install the module that uses the plugin.

Unable to parse at line 61 (near "  start: 5").' in /var/beetbox/core/lib/Drupal/Core/Config/FileStorage.php:117

Currently I'm looking into using explode, but this is certainly not an ideal solution. Does anyone have some insight on why this plugin wouldn't work? It works fine without using this plugin.

Update : It does seem that was the problem. Thanks for the help.

Answered at https://www.drupal.org/node/2829462 - as mradcliffe says, this is a YAML syntax error.


Setting up file sharing in Drupal 7 I would like to set up simple file storing and sharing (for educational purposes) for my users. I considered creating Profile2 profile and put data uploads files there. But it seems little clumsy.

Now i have idea to set up content types "File" Which will contain title and File upload field. That way they could possibly be able to "send" those nodes to anyonther somehow.

I could create listing of user files with views or else.

I am also using User Relationships module.

Question:
What would you suggest, what would be best method to achieve this ?
Is there mechanism for user to "send" node to another (User Relationships) ?
What is the danger of having extreme number of nodes that user can produce this way ?
Is there an alternative ?

Thanks

I suggest using Privatemsg module it had a nice attachment field and now it is fieldable that means you can add highly customizable file fields.

Thou Privatemsg module will work not as content type but more like internal messaging tool I also suggest checking out Notifications which depends on Messaging module. It will send emails upon creation or edit of chose content for all users you chose. You may also look into Team Notifications module which will allow your users to create subscriptions for others. Which is integrated with Organic groups module (OG). OG is best way for grouping and allowing users to group themselves yet if you are looking for a simple solution this may not fit due to it`s extensive functionality which results in fairly complex results.


Update customer billing address within custom pane I am writing a custom CheckoutPaneBase within Commerce 2 that incorporates shipping and billing information. My goal would be to update the customer's billing address, that is stored as billing profile, programmatically. I looked at the billing information Pane and see that they use:
  $billing_profile = $this->order->getBillingProfile();
      if (!$billing_profile) {
        $billing_profile = $this->entityTypeManager->getStorage('profile')->create([
          'type' => 'customer',
          'uid' => 0,
        ]);
      }
      $billing_profile->populateFromProfile($payment_method_profile, ['data']);
      $billing_profile->save();
      $this->order->setBillingProfile($billing_profile);

But rather that populate from $payment_method_profile, I would like to add my own fields' values. I am not sure how I can populate an array to push to populateFromProfile or setBillingProfile or the field values.
Any help or hints?

You can update the field value like this:
  $cart_provider = \Drupal::service('commerce_cart.cart_provider');
  $cart = $cart_provider->getCart('default');
  $billing_profile = $cart->getBillingProfile();
  $billing_profile->field_name->value = 'Hello World';
  $billing_profile->save();


How do I maintain aspect ratio of scaled image with max-width? When I use an Image Style that scales the original image, Drupal 7 (now 7.14) prints the height and width attributes in the img tag whereas before it didn't.
So before, my CSS img {max-width: 100%;} preserved the images aspect ratio when displayed in a small box (i.e. on a mobile screen), but now clashes with height and width attributes. Drupal generates enclosing boxes with no explicit height so the result is an elongated distortion.
What can I do - preferably with CSS alone, but in a template file's php if necessary - to preserve the aspect ratio?

It's as simple as just adding height:auto;

img {
max-width:100%;
height:auto;
}


Book: Drupal 7 Module Development (directions caused weirdness) I'm reading a book, Drupal 7 Module Development, and I'm hitting some very weird outputs.

I created a folder:

mysite/sites/default/module/first

Inside this folder I created two files.

first.info

;$Id$

name = First
description = A first module
package = Drupal 7 Development
core = 7.x
files[] = first.module

;dependencies[] = autoload
;php = 5.2

first.module

<?php

// $Id$

/**
 * @file
 * A module exmplifying Drupal coding practices and API's.
 *
 * This module provides a block that lists all of the
 * installed modules. It illustrates coding standards,
 * practices, and API use for Drupal 7.
 */

/**
 * Implements hook_help().
 */
function first_help($path, $arg) {
    if ($path == 'admin/help#first') {
        return t('A demonstration module.');
    }
}

But when I activate the module, I get the contents of the first.module file spashed across the top of my page? Can someone advise me on what I am doing wrong?

This is my very first module for Drupal.

You just have to follow the steps which I am writing below to create a module.

Go to folder SITES/ALL/MODULES
Create a folder for module, suppose mymodule
Inside that folder create a file name mymodule.info
Write these lines in there:

name = My Custom Module

core = 7.x

description = Custom module created for testing.
Create another file named mymodule.module
Just open the PHP tag like <?php and save the created .module file
Visit your module list & you will find this module in the list over there. If not then clear the cache for once.

Problem with your process which I saw is with the path which you followed for creating the folder for your module which SITES/DEFAULT/MODULES, which is not correct.


Hide/mask link URL in the web browser I'm new to Drupal and here is the requirement - There is a page that has a field (Doc link) of type Link. I give the URL of the Doc link field as /sites/default/files/docs/file1.html.
Now when I click on this Doc link field it shows the entire folder structure of file1.html in the web browser. I don't want users to see the actual path where file1.html is stored. I want to be able to mask/hide this URL in the web browser.
So instead of displaying https://xyz.com/sites/default/files/docs/file1.html I want to display a generic link - https://xyz.com/docs/latest/file1.html. Is there any module that I could use to achieve this?

It sounds like you want to store the file in Drupal's private file system.  There is no need for a module - this is in core.
Files that are in the private system will:

Be protected from access by Drupal's core access control system. If the user don't have access to the page where the file field is attached, he/she will not have access to  the file.
The URL will not be generally usable. (i.e. the link will be displayed in the browser's  address field, but only works "inside" Drupal).
If you place your private files outside the webroot (strongly recommended), they can only be accessed through Drupal's access control system. There is no real URL that can be guessed.

There is plenty of tutorials about setting up and using a private file system in Drupal [GIYF].  Here is a link to one example:
https://www.cmsdrupal.com/blog/how-secure-private-files-drupal-tips-safely-configuring-your-file-system


How to port vertical tabs functionality for custom node module to Drupal 7? I have a custom module (written for Drupal 6) which defines a new content type. In Drupal 6 I have used several fieldsets and Vertical Tabs module to have the custom node form more clearly laid out. It looked like this

$form['event'] = array(
    '#type' => 'fieldset',
    '#title' =>  t('Event'),
    '#weight' => -2,
);

While porting that module to Drupal 7, I altered that section to use the now-in-core functionality to

M$form['event'] = array(
    '#type' => 'fieldset',
    '#title' =>  t('Event'),
    '#weight' => -2,
    '#group' => 'vt_event',
    '#collapsed' => true,
    '#collapsible' => true,
);
$form['vt_event'] = array(
    '#type' => 'vertical_tabs',
);

This indeed works just fine, when converting up to three fieldsets to the new structure. However, my form is more complex and I need at least five additional fieldsets. But as soon as I convert the fourth fieldset to enable it for vertical tabs, I suddenly get 500 server errors.

Does anyone have any idea why this is happening? It's always the fourth fieldset when it breaks the site and it's regardless which fieldset is the fourth (I tried to enable three other fieldsets first, but again it breaks on the fourth one which worked before).

While driving me nuts yesterday, I started over again today and cleaned up the module a bit.
During that I tried to add another vertical tab again (#4) and this time it worked. By accident, I did re-use a group name and by this I finally was getting fully aware of how this is intended to work.

My mistake was to create a form element of type "vertical_tabs" for each first-level fieldset. But it is sufficient to only have on "vertical_tabs" form element and assign all fieldsets to that group (they actually are grouped then).

So, everything is fine with my code above but the last three lines are only required once.


How to access block fields programmatically? I display a block of type Assignment on the top of a page when I'm creating a node of type Submission.  I need to access the fields of the Assignment block programmatically with my custom module.

Are there any built in Drupal functions that will allow me to do so?

I'm currently using hook_form_alter() but that does not give me access to the block elements.

I found the value by first grabbing the assignment value from the URL, then looking up the path to find the node id, then loading that node and using a wrapper to find the value of that specific field.

        $url = $_SERVER['REQUEST_URI'];
        $pos = strpos($url, '?') + 1;
        $assignment = substr($url, $pos, strlen($url)); //get the assignment from the URL

        $nodeID = drupal_lookup_path('source', "student-assignments-new/" . $assignment);//get the path from the assignment - e.g. node/145
        $pos = strpos($nodeID, '/') + 1;
        $nid = substr($nodeID, $pos, strlen($nodeID));//get the node id

        $node = node_load($nid);

        $wrapper = entity_metadata_wrapper('node', $node);
        $fieldValue = $wrapper->field_file_type_text->value();

        $output = $node->field_file_type_text[LANGUAGE_NONE][0]['value']; //field_file_type_text is my own field name
        return $output;


Why can't I add an existing field to the user accounts on Drupal 8? On Drupal 7, you can add fields that have been added to nodes to user accounts.  At admin/config/people/accounts/fields, scroll down to Add related fields and simply select the field, easy.

But in Drupal 8, at /admin/config/people/accounts/fields, I see no option to add an existing field, just Add Field, which adds a new field.

Has this option been removed from Drupal 8, and if so, why?

Yes this option has been removed, a field cannot be shared across entity types.

You can, however, add the same field again, I.e. use the same name. Whilst they will share a name, they will be separate fields.

The reason for this is storage. In drupal 7, field storage was separate to entity storage, which meant a mismatch. In drupal 8, entity storage also handles field storage. This means if for example mongodb wants to store an entity and it's fields as a single blob/document - it can. On drupal 7 this would have required two blobs, one for the entity and one for the fields.


How to create a theme function for custom HTML markup and then call it in my node template? Ive created an asses for my site in the content type tpl file. Its mainly HTML but also some simple PHP. What are the steps to move this to a theme function?

You should be able to use the template_preprocess_node function to move your logic from your tpl files into the theme function. In order to use the function, replace template with the name of your theme.

function mytheme_preprocess_node(&variables){
  if($variables['node']->type == 'my_content_type'){
    //change what you want to the node here.
  }
}

You could do the logic you need to inside this functionn, save the output to a variable in $variable (it's a reference var, so it dosn't need to be returned) and then just print out that variable in your tpl.php file.


How do I allow access to my custom module to "anonymous user" case :

I have created a custom module
Implemented a hook_menu() as shown

  function my_custom_menu() {

  $items = array();
  $items['my/custom/link'] = array(
    'title' => t('My Custom Form'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_custom_user_form'),
    'access arguments' => array('access content'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );
    return $items;
}

But problem is that "anonymous users not able to access link"

Please guide me...

I would suggest you gain more control over the access, by switching to "access callback" => "my_custom_function".

Then in my_custom_function() you can write just "return true" which will make it always accessible.

You could also add a log before "return true" so you can  tell whether the function is being called. If it isn't, then you know access is being blocked further up, before you get to that stage.


Change Add To Cart To Buy Now drupal Commerce Hello currently I am making a online e store using drupal Commerce so i want to change add to cart button to Buy Now So Ho Can I able To Do Help It Out

If you want to alter the text for a particular form you can alter it using hook_form_alter

Get the ID of the form for the product display where you are trying to change the text & do something like this:

function MYMODULE_form_alter(&$form, &$form_state, $form_id){//replace your module name with MYMODULE
  if(strpos($form_id, 'commerce-cart-add-to-cart-form-65') !== false){//my form ID is "commerce-cart-add-to-cart-form-65", replace it with your form ID.
    $form['submit']['#value'] = t('Buy Now');//Put the text which you want to make appear instead of "Add to cart".
  }
}

You could also use String Overrides Module to achieve the same.


How should I deal with a vocabulary with many terms? I'm trying to use Drupal 8, but if Drupal 7 is better for that, I'm ready to go back to Drupal 7.

I have a vocabulary that must contain at least 10,000 terms, but they can also become more than 100,000.  For the sake of simplicity, I chose to make only one vocabulary, without hierarchy.

I quickly reached the limits of my server, and I regularly get WSODs,  especially when I try to edit the vocabulary.

I tried to increase the limits of memory (I am under MAMP), but I still have errors. Here is the error:

  Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes) in /core/lib/Drupal/Core/Entity/Sql/Sq

How can I avoid these problems?
Is it preferable to split the vocabulary?

Since i can't answer it in comment. i'll try to answer here. I've solve similar problem, my solution is using redis caching and entity cache module

Since then, my site going well with 256MB RAM configuration in php.ini.


Views: apply filter only if a condition matches I've searched a lot the Views issue queue, searched for other modules, searched on stackexchange, but it seems that no one needs this functionality (or that there's another way to achieve it).

Use case:
I have two content types: lecture and substitute teaching. A teacher uses the lecture content type when he has a normal lecture in a class where he has a chair. A teacher uses the substitute teaching when another teacher isn't at school (ill or in an excursion) and he has to replace the colleague.

In the lecture content type I have put an entity reference field named "chair", which filters the chairs so only the tearcher's ones are shown. For doing this I use the entity selection section of the field, and pass via token the teacher's uid to the view. But in the substitute teaching content type, I don't want to filter the chairs. Since a teacher could replace anyone, I need an unfiltered list of chairs.

Since the entity selection part of the field is applied everywhere this field is used, I had to create another entity reference field in the substitute teaching which references the chair content type, but without filtering. Having the same content type pointed, but using two different fields, is leading to maintenance nightmares (put both the content types and filter them based on chair field is nearly impossible), so I'm seeking for a different approach.

I think that a good one would be to pass to the view the uid and the content type. If the content type is "lecture", then apply filtering, otherwise don't. In this way I could use the same field in both the content types and everythig would work smothly. Well, it seems impossible to do such a simple thing.

The only solution that got me near the desired result was using conditional fields, but when filtering I got a bunch of empty option values where the view result was hidden, but it was selectable.

Any help or hint would be appreciated. Thanks!

You will have to add a custom module for this. I usually have one monolithic module that I add to every project that I name the same as my project for project specific tweaks like this.

In that module's module file, add this code:

function MODULE_views_query_alter(&$view, &$query){
  // target the correct view
  if ($view->name == 'chair' && $view->current_display == 'entityreference_1') {
    // target the correct path
    $node = menu_get_object();
    if ($node && arg(0) == 'node' && arg(2) == 'edit' && $node->type == 'lecture') {
      // edit page on lecture type
      $view->query->add_where("entityreference_tweak", "node.uid", $node->uid, '=');
    }
    else if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'lecture')
    // create page on lecture type
    {
      global $user;
      $view->query->add_where("entityreference_tweak", "node.uid", $user->uid, '=');
    }
  }
}

I named the entityreference view 'chair', the entityreference display took the default name 'entityreference_1', the lecture content type has the machine name 'lecture'. You need to substitute these name in the code above with your own machine names.

Then completely remove the contextual uid filter from your entity reference view and also do not pass anything to the view in the field settings of the content type. The code adds the filter dynamically. It checks if you are on a lecture edit/add page, then adds either the node author uid, or the uid of the currently logged in user.


How to insert form into node/add page I am currently developing a module with a custom content type. In the node/add for this content type, I need to be insert a form that can retrieves data from an API, that will later be displayed on the page.

What is the best way to insert that form into the node/add page?

Should I use a hook_form_alter? Or should I make a custom field? This portion of the form will most likely involve AJAX, so I don't know if that will change anything.

Let me know if I need to clarify anything, and thanks in advance!

Whether you create a custom field then modify it later, or create it completely in code, you need to use hook_form_alter in your custom module and add/edit your field that way and add the ajax call inside this function.

If you create a custom field in config, then there's now a config dependency you will need to somehow move from your dev environment to production (either thru Features or Configuration modules). On the other hand, if you add all through your custom module you won't need to worry about config changes, so IMO that is a better way.


How can I render a field inside a tpl.php that is hidden on the UI I have a taxonomy field attached to a content type. On the teaser view mode, the field is hidden. I have two sections where I display the content type's teasers. On one section I don't want the terms to show. On the other section, I want them displayed.

I would like to know how I can render this field from the template node.tpl.php. It's not available as an element of $content, but is attached to the $node object.

Thanks

You can add any markup or additional fields to the node teaser view or node full view using hook_node_view().
The following example is adding a taxonomy name to the teaser view.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'teaser'){
     $tname = db_query('SELECT name FROM {taxonomy_term_data} t WHERE tid = :tid', array(':tid'=>$node->field_category['und'][0]['tid']))->fetchField();
     $node->content['my_taxonomy'] = array(
        '#markup' => '<div>'.$tname.'</div>',
        '#weight' => 10,
      );
    }
}

You would not need to update node.tpl.php.


How make a standalone field with no Entity or Bundle? I want to add a custom configuration form to my module; I don't know if making a custom schema is better or if I should make a standalone field and use its different field APIs to deal with the value.

Can I create a standalone field with no entity or bundle? If I can't, what would be the alternatives?

Take a look at system_settings_form and how it is used by other modules to create a basic form and field for module configuration. It'll generally use variable_get and variable_set to get and store it's value.


How to get the nodeid in node_grants so that it works in a view? I am exploring the node_grants and node_access_records with the following objective:

I want to be able to hide nodes where the current logged-in user is not 'friends' with the node author. The node author selects if they want to limit it to friends or not with a boolean field. Here, the subtlety is that there are a few views which list nodes on my site, so I want it to work for views too.

I am using drupal 7, user relationships for the 'friends' relationship and here is my node_grants code. How do I get the node id, especially in the context of views?

function mymod_access_node_grants($account, $op) {
// Grants all rights if the author
$grants['mymod_access_author'] = array($account->uid);

    $value_friends = field_get_items('node', $node, 'field_friends_only');
    $value_friends = $value_friends[0]["value"];
    $value_friends = 1;

    if ( $value_friends == NULL) {
        $value_friends = 0;
    }
    if ($value_friends == 0) {
        $grants['mymod_access_public'] = array(1);
        $grants['mymod_access_friends'] = array(1);
        $grants['mymod_access_notfriends'] = array(1);

    } else if ($value_friends == 1)  {
        //if node is for friends only, then check if relationship exists...
        $current_user_uid = $account->uid;
        $node_author_uid = $node->uid;

        // Set up the parameters
        $params = array('between' => array($current_user_uid, $node_author_uid));

        // Get the relationships
        $relationships = user_relationships_load($params);

        if ($relationships) {
            $grants['mymod_access_public'] = array(2);
            $grants['mymod_access_friends'] = array(2);
            $grants['mymod_access_notfriends'] = array(2);
        } else {
            $grants['mymod_access_public'] = array(3);
            $grants['mymod_access_friends'] = array(3);
            $grants['mymod_access_notfriends'] = array(3);
        }
    } else {
    }
}

return $grants;
}

PS: although I have $node in my code, it is empty at the moment!

You actually need to implement two hooks:

hook_node_grants() which returns the grants a user has
hook_node_access_records() which returns the grants a node needs

It's the second hook that gets a node object, not the first. Keep in mind that you need to implement both the hooks.

As for hook_node_access(), this hook is called when a node is fully loaded, and it not called for node listings, as reported in the documentation.

  Also note that this function isn't called for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.) See Node access rights for a full explanation.

As for views, a view doesn't full load a node, but executes a SQL query to get node data. merlinofchaos clearly states it in Views does not respect hook_node_access.

  hook_node_access() is something that is run after a node is fully loaded. Since Views is loading nodes via query, you can't get the query to respect it unless you also use hook_db_rewrite_sql() which is what Views hooks into.

  This is not true of just Views, but any query that loads nodes. For example, the default Drupal front page will not respect hook_node_access() that isn't paired with hook_db_rewrite_sql() any better.

  hook_node_grants() and hook_node_access_records() will be used, however, if you set "Disable SQL rewriting" then you are specifically skipping that stuff.

Notice that hook_db_rewrite_sql() is not used from Drupal 7 and higher, though. The equivalent for Drupal 7 and higher is hook_query_alter().


Term reference list with a field for extra information For a site I'm working on I have a functionality in mind that I simply cannot wrap my head around as to how I would set it up.
When creating content of a specific content type I want to have the option to select multiple items using checkboxes from a list of about 30 items, and have the option to add a short piece of text (less than 20 characters) to each of these items if I want to.

Currently I have no real idea on how to set this up. I'm planning on adding the 30 or so items to a vocabulary so I can easily reference them, but how would I be able to select these items and add the piece of text so it's linked to these items as well?

Basically what I'm looking for is the following:

I hope someone is able to shed some light on this for me, any help is appreciated.

As far as I know you can achieve that in two ways.

Using the combination of Double Field and Field group modules.

  Use "Double field" for to make list of checkbox and textfields, and Field Group to make all of them a Group.

There is another option to achieve this. Try the Composed Field module

  Composed Field is an implementation of core's Field UI that allows you to split a single field into as many sub-fields as you like.

This seems very close to your requirement. I've used this one of my project and working fine.


How can I add a class with table theme function to a table header row? How can I apply a class to the
 of some table headers using the table theme function?

So, I get this:
foo	bar

...rather than:
foo	bar

...which is all I've managed with this:

$section = array(
  '#theme' => 'table',
  '#header' => array(
    array('data' => 'foo', 'class' => 'my-class',),
    array('data' => 'bar', 'class' => 'my-class',),
  ),
  '#rows' => $rows,
),

Thanks

If your current example works I'm assuming you are on drupal 6.

You can add attributes to the header array like this:

$section = array(
  '#theme' => 'table',
  '#header' => array(
    array('data' => 'foo', 'class' => 'cell-class'),
    array('data' => 'bar', 'class' => 'cell-class'),
    'class' => 'row-class',
  ),
  '#rows' => $rows,
),


Loop through array in Twig I have this array

{% set icons = { 1: 'glyphicon glyphicon-asterisk',
                 2: 'glyphicon glyphicon-plus',
                 3: 'glyphicon glyphicon-minus',
                 4: 'glyphicon glyphicon-euro'
                 }
%}

I want to loop through it and print like this

<li{{ item.attributes.addClass('pos' ~ loop.index, icons[loop.index]) }}>

Simple:

Twig:

<ul>
  {% for key, icon in icons %}
    <li{{ item.attributes.addClass('pos' ~ key, icon) }}>
  {% endfor %}
</ul>

Source:
http://twig.sensiolabs.org/doc/tags/for.html


Caching options and modules My guess is that many ppl like me make Drupal websites just by using modules and simple CSS. Several content types, taxonomies, views, panels or DS to get results fast and more/less nice looking. Maybe add forum to all that.

When it comes to caching there are many options and i have no idea which ones to use. All my websites are on shared hosting (most popular ones).

In "performance" i always enable everything.
Minimum cache lifetime and expiration of cached pages are options i always gaze at for several minutes and in the end choose "1 day". No idea if thats good.
All other check boxes are clicked of course.

Views 3 are cached by default, nice, if i remember good i had to enable that in previous versions.

Now the fun part is picking modules from drupal.org for caching.

On this page Caching: Modules that make Drupal scale (updated 2014-07-09) we have 15 modules for D7. How many to use ? Which ones are "best" ? Which one you reccomend for shared hosting ? Should i for example disable default caching in performance and in views if i use those ?

So the final question would be: For nondevelopers who use shared hosting, what are the easiest/best modules - plugnplay.

I have usually used the Boost module. It provides a lot of functionality and works really well, but can be a bit to set up since many times you have to modify .htaccess files when rules changes are made. I've used Boost for many sites where Varnish or some other server-side solution was not available and the results were satisfactory. Keep in mind that boost will not work when authenticated --- in fact many caching solutions will not. But Boost does have other modules to help cache authenticated pages for users.


Can't add instance of custom field type to entity I have a custom field type that I'm trying to add to a custom fieldable entity. The entity works fine and I've added other fields to it, my problem is when I go to add an instance of my field to the entity, I get the following SQL error:

  There was a problem creating field Authors: Exception thrown while
  performing a schema update.
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NOT NULL, PRIMARY KEY (entity_id, deleted, delta, langcode), INDEX bundle' at line 9: CREATE TABLE {myentity__field_myfield} ( bundle VARCHAR(128) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '' COMMENT 'The field instance bundle to which this row belongs, used when deleting a field instance', deleted TINYINT NOT NULL DEFAULT 0 COMMENT 'A boolean indicating whether this data item has been deleted', entity_id INT unsigned NOT NULL COMMENT 'The entity id this data is attached to', revision_id INT unsigned NOT NULL COMMENT 'The entity revision id this data is attached to', langcode VARCHAR(32) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '' COMMENT 'The language code for this data item.', delta INT unsigned NOT NULL COMMENT 'The sequence number for this data item, used for multi-value fields', field_myfield_target_uid INT unsigned NOT NULL COMMENT 'The user ID of the author', field_myfield_affiliation NOT NULL, PRIMARY KEY (entity_id, deleted, delta, langcode), INDEX bundle (bundle), INDEX revision_id (revision_id)  ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT 'Data storage for myentity field field_myfield.'; Array ( )

I've replaced my entity with myentity and my custom field type with myfield for the above. My schema definition for my field type is as follows:

/**
 * {@inheritdoc}
 */
public static function schema(FieldStorageDefinitionInterface
$field_definition) {

  $columns = [
    // List the values that the field will save. This
    // field will only save a single value, 'value'
    'target_uid' => [
      'type' => 'int',
      'not null' => true,
      'unsigned' => true,
      'description' => "The user ID of the author"
    ],
    'affiliation' => [
      'type' => 'varchar',
      'size' => 255,
      'not null' => true
    ]
  ];

  $schema = [
    'columns' => $columns,
    // 'indexes' => [
    //   'target_uid'
    // ],
    // 'foreign keys' => [
    //   'target_uid'
    // ],
  ];

  return $schema;
}

I've looked at other core field types for guidance but I can't see where I'm going wrong.

You’re confusing the required length property of a varchar field with the size property of a text field.

Replace size with length (or varchar with text if that makes more sense) and your code should start working.


Add class to taxonomy term in view I got a view listing nodes of the content type "Job". Every node is tagged with different "Jobtypes" that are listed too. Now I want to style every taxonomy different (colors, icons, etc.) so it would be nice, every taxonomy would have his own class. At the moment I don't see a way to do this. Some ideas? Thank you!

Relationship: Choose "Content: Taxonomy terms on node" & "Jobtypes"
Field: Add "term id"(Exclude from display) with relationship
Field: Add Jobtypes Field and "Rewrite the output of this field" with token

such as:

[field_jobtypes]

will get each term with unique css class with its term id.


How to fetch fields in a view in the overrided twig file? I have created a view like so:

I have written a twig file for it named
views-view--employee_details--block_1.html.twig, which is placed in folder /project_name/themes/theme_name/templates/views.

I want to fetch fields from the view into
views-view--employee_details--block_1.html.twig file.

How can I do so?

You can do it like this:

{{ fields.[machine_name].content }}

The machine name is shown in your content type manage fields.

So it would be:

{{ fields.title.content }}
{{ fields.field_designation.content }}

Also, your template name needs to be: views-view-fields--employee-details--block-1.html.twig

Make sure you clear/flush the cache to see the changes.


Case difference of Usernames; how to login with Usernames regardless of case in Drupal 7 Quick question.

On my site, users have entered their username with capitalized case or mixed upper or lower cases during registration. Now when the Login, they forget that write everything lower cased and ofcourse that doesn't work making things difficult for me.

so my humble question is, how do I validate the login regardless of case?

Thanks a lot.

There are no modules that I know of at this time that provides this functionality.  It can be done, however, by writing a custom module.

I suggest that you look at LoginToboggan as a model for how to write your own module.  The basic flow is this:

LoginToboggan allows users to log in using either their username or email address.  Drupal, by default, does not support logging in with an email address, so LT does a hook_form_alter() to add a function to the login form's #validate.
The Validate function, logintoboggan_user_login_validate() searches for an email address that matches the one provided by the user.  If it is found, then LT provides the username to the form programmatically.
Because the username is provided during the #validate step, the form flow continues and processes the username which was retrieved by LT, and the user is logged in.

Your solution would follow a very similar flow, but instead of checking for an email address, you would check against username.  The LT function uses a LOWER() SQL function to recognize differences in capitalization in the email; you will do the same, except with usernames.

One addition that you may have to make is that, if you allow users to register themselves on your site and pick their own usernames, you may need to ensure that the selected username does not collide with a capitalized version (e.g, Drupal may allow a username mrawesome and MrAwesome because they are different, but you should disallow the latter because they are viewed as equivalents within the confines of your system).


How do I sync taxonomy terms with the second level of a menu? This question pops every time I create a new e-commerce site.

I have a horizontal main menu with Home, Products, Blog, etc... in it. I need to get the terms from my Product catalogue as the drop down menu underneath Products.

I use Taxonomy Menu to good effect elsewhere in the site, but I can't see any way of moving an entire Taxonomy Menu (or even a sub-set) to underneath a menu link in another menu.

My usual method is to hard-code a function into my theme (with appropriate caching of course), which builds up the sub-menu of terms. I then have to create another function to mimic the menu rendering functions, and inject the 'taxonomy menu' when my loop hits a certain menu link ID. Finally I use that function in place of the standard method of outputting menu links in my page template file.

Needless to say that's not a good method and it leaves me feeling dirty every time. I'd really prefer a more opaque method that keeps the menu in sync when terms in the vocabulary are changed.

It seems like this problem would have been solved over and over again, but my Google-fu is failing me.

Anyone got any good suggestions (that don't involve creating a View, which would be way too much overhead)?

I should also mention the lazy man in me is looking for a pre-built module to do this. It would be fairly trivial(ish) to implement the code on a case-by-case basis (see hampusn's comment below) but I'm hoping there's a generic module based solution available.

I used this on a site a few months ago to essentially do the same thing:

function _foo_add_submenu ($menu_name, $vid, $plid)
{
  $vocabulary = taxonomy_vocabulary_load($vid);
  $tree = taxonomy_get_tree($vid);

  if (count($tree) > 0) foreach ($tree as $term) {
    $item = array(
      "link_path" => "taxonomy/term/{$term->tid}",
      "link_title" => $term->name,
      "menu_name" => "menu-menu",
      "plid" => $plid,
      "router_path" => "taxonomy/term/%",
    );

    $sql = "
      SELECT menu_links.mlid
      FROM {menu_links} menu_links
      WHERE menu_name = :menu_name AND plid = :plid AND link_path = :link_path
    ";

    $result = db_query($sql, array(
      ":menu_name" => $menu_name,
      ":plid" => $plid,
      ":link_path" => $item["link_path"],
    ));

    $record = $result->fetchObject();

    if (isset($record->mlid) && $record->mlid > 0) $item["mlid"] = (int) $record->mlid;

    menu_link_save($item);
  }

  menu_cache_clear_all();
}

$menu_name is the menu to mess with, $vid is the vocabulary to build from, and $plid is the item to add to.  When you run this, you will end up with a real menu in admin/structure/menu/manage/menu-whatever.  You will need to add some additional housekeeping functions to handle adding terms, removing terms, etc, but they all involve similar functions and menu_link_save / menu_link_delete and menu_cache_clear or menu_cache_clear_all being called from the right taxonomy hook.


Custom language that displays content from two languages This is a rehashing of a question I asked previously, but maybe asked the wrong way.

I have a multilingual Drupal 7 site - there are 13 different languages and those sites all have unique translated content on them.

However, there are an additional 5 "languages" we need to account for - an example of this would be Australia. Australia speaks English so we'd like it to display English content, but there is also content that is unique to Australia (which can't display on the English site), so that should be displayed on the Australian site as well.

I'm curious if we can define a custom language (Australia) that can display multiple types of language content (English and Australian).

For example:

Australian Website

Home (English)
About (English)
Products (English)

Product One (English)
Product Two (English)
Product Three (Australian)
Product Four (Australian)

Resources (English)
Contact (English)

Hopefully this makes sense. Any insight is appreciated.

The whole idea of linking language with country falls apart when you consider countries like Canada. You could separate language and applicable country since they're not really the same thing. In your example:

Australian Website

Home (Lang: English - Country: UK, US, Canada, Australia)
About (Lang: English - Country: UK, US, Canada, Australia)
Products (Lang: English - Country: UK, US, Canada, Australia)

Product One (Lang: English - Country: UK, US, Canada, Australia)
Product Two (Lang: English - Country: UK, US, Canada, Australia)
Product Three (Lang: English - Country: Australia)
Product Four (Lang: English - Country: Australia)

Resources (Lang: English - Country: UK, US, Canada, Australia)
Contact (Lang: English - Country: UK, US, Canada, Australia)


ShippingOrderProcessor not registered well? I'm trying to implement @jsacksick solution which should force displaying shipping costs on cart page (normally it doesn't exist at that step yet). I created a new module for this and it's structure is simple:
shipping_fix
  src
    ShippingOrderProcessor.php
  shipping_fix.info.yml
  shipping_fix.module
  shipping_fix.services.yml

ShippingOrderProcessor.php is exact copy of @jsacksick class:
https://gist.github.com/jsacksick/fde031197df92236ef5a916775e17a2e
info file contains:
name: Shipping fix
description: Fixes missing shipping info on cart page
type: module
core: 8.x
dependencies:

module file is empty and services file contains:
services:
  shipping_fix.shipping_order_processor:
    class: Drupal\shipping_fix\ShippingOrderProcessor
    tags:
      - { name: commerce_shipping.shipping_order_processor, priority: -300 }

But it's not working. I tried setting break points inside __construct() and process() methods of that class, but they are never reached.
Tried changing last row here to:
 - { name: commerce_order.order_processor, priority: -300 }

as explained here: https://docs.drupalcommerce.org/commerce2/developer-guide/orders/order-refresh-and-process
but then my site crashes when I try to clear the cache?
So to me it looks like that I didn't register this processor object well. Most likely problem is in services file, but I can't figure out what it is ("commerce_shipping.shipping_order_processor" is correct value?).
Tried dumping services with drush like:
drush devel:services
drush devel-container-services
drush devel-services

and even devel mode is turned on for each try I get:
Command "devel-container-services" is not defined.
or similar.
I activated the my module of course, tried clearing caches, but didn't help.
Update:
The error which I get when I change last row of services file to:
 - { name: commerce_order.order_processor, priority: -300 }

is:
Service 'shipping_fix.shipping_order_processor' for consumer 'commerce_order.order_refresh' does not implement Drupal\commerce_order\OrderProcessorInterface.
And ShippingOrderProcess.php file starts with:
<?php declare(strict_types=1);

namespace Drupal\my_module\OrderProcessor;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\OrderProcessorInterface;
use Drupal\commerce_shipping\ShipmentManagerInterface;
use Drupal\commerce_shipping\ShippingOrderManagerInterface;
use Drupal\profile\Entity\Profile;

/**
 * Ensures there are shipments from the start.
 */
final class ShippingProcessor implements OrderProcessorInterface {

  /**
   * The shipping order manager.
   *
   * @var \Drupal\commerce_shipping\ShippingOrderManagerInterface
   */
  protected $shippingOrderManager;

  /**
   * The shipment manager.
   *
   * @var \Drupal\commerce_shipping\ShipmentManagerInterface
   */
  protected $shipmentManager;

  public function __construct(ShippingOrderManagerInterface $shippingOrderManager, ShipmentManagerInterface $shipmentManager) {
    $this->shippingOrderManager = $shippingOrderManager;
    $this->shipmentManager = $shipmentManager;
  }

...

Update 2:
Managed to clear the cache:
For my file structure name space has to be:
namespace Drupal\shipping_fix;

Also changed servies file and now it looks like:
services:
  shipping_fix.shipping_order_processor:
    class: Drupal\shipping_fix\ShippingProcessor
    arguments: ['@commerce_shipping.order_manager', '@commerce_shipping.shipment_manager']
    tags:
      - { name: commerce_order.order_processor, priority: -300 }

Now cache clearing works, but I still don't see shipping costs on cart page...

In this case, you'll want to run this before the commerce_shipping.early_order_processor, set priority to 300
services:
  shipping_fix.shipping_order_processor:
    class: Drupal\shipping_fix\ShippingProcessor
    arguments: ['@commerce_shipping.order_manager', '@commerce_shipping.shipment_manager']
    tags:
      - { name: commerce_order.order_processor, priority: 300 }


remove fivestar rating from $print['content'] in print module I installed the print module. But in the print view, the fivestar rating of the node is shown. How can I remove it?
It seems to be in $print['content']. Any help appreciated.

go to your content type manage display page and enable the custom display for the print view mode: http://prntscr.com/e0k5d6
go to newly enabled print custom display and hide your fivestar field: http://prntscr.com/e0k633


How to export all feature components with drush? With drush feature-export you can easily create a feature from a component. But is there a way to easily export ALL components into a feature? In the ui you can easily check all content types or all views. I tried drush fe newfeature views_view but it only exports one view not all of them.

Hmm ... did you try drush's built in Help topics?

I am running drush --version:
Drush Version   :  6.2.0

The help output for features-export is:
drush help fe

Export a feature from your site into a module. If called with no arguments, display a list of available components. If called with
a single argument, attempt to create a feature including the given component with the same name. The option '--destination=foo'
may be used to specify the path (from Drupal root) where the feature should be created. The default destination is
'sites/all/modules'. The option '--version-set=foo' may be used to specify a version number for the feature or the option
'--version-increment' may also to increment the feature's version number.

Arguments:
 feature                                   Feature name to export.
 components                                Patterns of components to include, see features-components for the format of patterns.

Options:
 --destination                             Destination path (from Drupal root) of the exported feature. Defaults to
                                           'sites/all/modules'
 --version-increment                       Increment the feature's version number.
 --version-set                             Specify a version number for the feature.

Aliases: fe

And drush help fc:

List feature components matching patterns. The listing may be limited to exported/not-exported components.

A component pattern consists of a source, a colon and a component. Both source and component may be a full name (as in
"dependencies"), a shorthand (for instance "dep") or a pattern (like "%denci%").

Shorthands are unique shortenings of a name. They will only match if exactly one option contains the shorthand. So in a standard
installation, "dep" will work for dependencies, but "user" wont, as it matches both user_permission and user_role.

Patterns uses * or % for matching multiple sources/components. Unlike shorthands, patterns must match the whole name, so
"field:%article%" should be used to select all fields containing "article" (which could both be those on the node type article, as
well as those fields named article). * and % are equivalent, but the latter doesn't have to be escaped in UNIX shells.

Lastly, a pattern without a colon is interpreted as having ":%" appended, for easy listing of all components of a source.

Arguments:
 patterns                                  The features components type to list. Omit this argument to list all components.

Options:
 --exported                                Show only components that have been exported.
 --not-exported                            Show only components that have not been exported.

Aliases: fc

So you should be able to use wildcards like % or * to select all types of a component. Eg, drush fe newfeature views_*. Your mileage may vary ...


What functionality is available from Drupal.theme() I have some complex data in javascript I need to render, mostly as tables.

This page explains how to add new theme functions, but I just want to create basic vanilla html. This apparently is the "official documentation."

I can't for the life of me find a list of the functions/functionality available in Drupal.theme()

I note this list of functions available from php - but I'm assuming the javascript version is a subset?

These are the JS theme functions defined by core:

Tabledrag

Drupal.theme.prototype.tableDragChangedMarker
Drupal.theme.prototype.tableDragIndentation
Drupal.theme.prototype.tableDragChangedWarning

Vertical Tabs

Drupal.theme.prototype.verticalTab

Overlay Module

Drupal.theme.prototype.overlayContainer
Drupal.theme.prototype.overlayElement

Many contrib modules also define their own theme functions, it's not possible to list all of those here so your best best is to run a grep -nr "Drupal.theme.prototype" /path/to/drupal and see what's available in your own installation.

It's also worth bearing in mind that individual theme functions will only be available in the page if the file that contains them has been included. So if the Overlay module is disabled, for example, the related theme functions won't be available. If the vertical tabs JS hasn't been added that won't be available, and so on.


Theming views fields with twig I have a search results view from Search API where I need to use the excerpt that highlights the keywords being searched. In this instance, that prevents me from using a view mode output as the result.

In this instance, I have a view set up to output title, URI, date modified and search excerpt. I have a decent bit of theming to do around the form and results, but I can't seem to figure out how to view both the template suggestions for each view field, or just theme it manually in the given template views-view--unformatted--search--results.html.twig.

I also tried {{ kint(row) }} and even when viewing on its own page, basically locked up my browser.

So for instance, for the title, I need the markup to be:

Foo Exam

For consistency reasons, I would like to control it from twig templates instead of attempt to do it in the views admin (setting label field etc settings).

You're probably looking for

views-view-fields--[view-name]--[machine-name].html.twig

views-view-fields--search--results.html.twig

In your view click on your title field and uncheck Link to the content.

then your template file

{{ fields.title.content }}

Not really sure if you really want # as href. I think you want to link to content. So add Path as a field.

{{ fields.title.content|striptags }}

Note: You'll probably want to use |striptags if you do not strip the markup from the views UI. Unless you do not mind having <divs> wrapping your title text.

then {{ fields.field_machine_name.content }} each of the rest of your fields that you want to output.

  Important: Make sure TWIG DEBUG is off, as it tends to screw up templates in Views.


Check if current page is taxonomy term How can I check if the current page is a taxonomy term page, similarly to what done with the following code used to check if the current page is the front page?

if (drupal_is_front_page()) {
  // The current page is the front page.
}
else {
  // It is not the front page.
}

Just to offer a solution that doesn't make use of arg() (which it's advised to avoid where possible according to the docs page)

You can use the menu_get_object() function:

$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  // User is on a taxonomy term page
}


Add image to taxonomy terms menu item My menu block is using the module: taxonomy menu terms to construct the main menu as a block to display in frontend.

I want to add image to each menu item, anyone know what is the simplest way to do that? or other module can do the same things?

Have you tried Menu Icons? It is useful.
If you want to add some custom image to every term, add the field into your entity and upload default image. But I think, this module works better.


How to display a specific page number of a views mini pager? I'm displaying a view on a pager with a mini pager. It has total number 15 pages.

I want to display page number 5 by default. The the next link will point to page number 6 and the previous link will point to page number 4.

I have tried the below code.

function mymodule_views_pre_execute(&$view) {
  $view->query->pager->current_page = 5;
}

It just moves the page number in the page number, displaying it as page 5 of 15 but the views displaying the results of the page 1.

It it possible to set the default page number of a pager? How?
I'm using ajax in views.

I have found the answer. I'm sharing here the solution.

I used the following code and it worked.

function mymodule_views_pre_build(&$view) {
  $view->set_current_page(5);
}


How to sort view search results by giving custom relevance weights? I am using Drupal 7.43 and core search module.

I use "Search: Search Terms" for filter criteria and "Search:Score" Sorting criteria in my view to sort my results according to relevance.

But, for example if I search for text "drupal view search" it prioritize some node containing word "drupal" 5 times over a node containing all the text I entered, "drupal view search".

I want to sort my results such that, prioritize nodes that have title as the text I entered,then nodes that have any of the words in title, then nodes that have that text in the body.

How can I customize and add more functionality to the content ranking part in this page /admin/config/search/settings?

Drupal core's search can't really do this. You'll need to use something like the Search API contrib module (https://www.drupal.org/project/search_api).

Search API allows you to plug in different backends ("servers") for the search database. I have the most experience with Solr, rather than the "database" backend. Solr, for sure, lets you not only choose which fields get indexed, but also how much relevance each field is awarded when a search matches. That is, you can say to index the title of the node as a Fulltext, with a score (weight) of 5, but index the body as Fulltext with a weight of 4.


How can you add the ID to the content type fields? All I see are classes, and from my understanding seems that there is nothing in the variables.

By default template_preprocess_field doesn't initialize the attributes array, so you don't see it when viewing the variables with the Devel module. You can achieve this and any other attributes by adding it in a template_preprocess_field() from your themes template.php file. When added it will get output to the field in template_process_field(). Here's a generic example of adding an attribute to a field. Swap all caps items for your use case...

/**
 * Implements hook_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
  $content_type = $variables['element']['#bundle'];
  $view_mode = $variables['element']['#view_mode'];
  $field_name = $variables['element']['#field_name'];

  switch ($field_name) {
    // We make sure it only effects the correct field ...
    case 'FIELD_MACHINE_NAME':

      // ... and, assuming you want to limit the where an id is used, we only add on a certain content type's full node page.
      if ($view_mode === 'full' && $content_type === 'CONTENT_TYPE_MACHINE_NAME') {
          $variables['attributes_array']['id'] = 'my-id';
      }
      break;
  }
}


How do I get the login link? I have a backup of a Drupal 7 website with its database. Is there any solution to get the login path? I have tried many options: /?q=user/login, /login, /user, and /user/login.

use drush command to login, it will print the login URL.

drush uli;


Lots of permissions errors, should the entire site be set to www-data? This is my first time configuring a lamp stack and I'm running into lots of problems with permissions. Here's an example of one of the errors

The specified file temporary://fileChLMzd could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

When I go to reports / recent log messages, this is all I can find:

REFERRER   http://localhost/boilerplate/public/admin/reports/dblog
MESSAGE File temporary://fileChLMzd could not be copied, because the destination directory public://js is not configured correctly.

I use to get a lot more of these errors when I had my temp directory inside of the apache installation, but I've since moved it to /tmp, which got rid of a lot of errors.

I've currently got my entire sites/default/files folder set to 777 with www-data access, which doesn't feel safe.. is this right?

Should everything else be set to have root access, like it currently is, instead www-data?

Stuff that I'm using:

Ubuntu 14.04
Apache2
MySQL
PHP 5.5
Drush status:
 Drupal version                  :  7.41
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database username               :  admin
 Database name                   :  boilerplate
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  boilerplate
 Administration theme            :  seven
 PHP configuration               :  /etc/php5/cli/php.ini
 Drush version                   :  5.10.0
 Drush configuration             :
 Drupal root                     :  /var/www/html/boilerplate/public
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Private file directory path     :  /var/www/html/boilerplate/private
 Temporary file directory path   :  /tmp

You should never give the files directory 777 permissions unless your workin on a local machine. Still then it is bad practice.

Every file in the system needs to be readable by the system user your webserver is using. Every directory should be readable, writable and executable by the same user. The same could be said for the webserver group.

I always set the user to my local user and the group to a group that is readable by my user account & the webserver account. The files directory (and his subdirectories) could be set to a simple 775 so the user and the group have permissions to it. All other users should only be able to read & execute the directory.
As for the files inside the files directory, they should be readable and writable to the local user and the webserver group & only readable for all other users. They should be set to 664.

The same could be said about your private directory, which I just noticed in your error post.


How to set a datetime field = now() during insert? I'm using db_insert() to insert a record into a table. That table as a "creationDatetime" field which should be set to now() on insert. I tried setting it to REQUEST_TIME, but that value is a unixtime value and not an sql datetime format so I get an error.

I suppose I could write a php function that will automatically format REQUEST_TIME as an sql datetime value and call that function every time I try to insert, but does anyone else have a better solution?

Using a slightly different syntax (drupal_write_record):

$new_record = array(
    'field' => $form_state['values']['field'],
    'timestamp' => date("Y-m-d H:i:s", time()), //<- this
);
drupal_write_record('table_name', $new_record);


Hide row in view if Content: Edit link field is empty I have a page view that table format. I have Content: Edit link field. I want to hide the row that contains that field empty. The following is a screen shot for Content: Edit link settings regarding NO RESULTS BEHAVIOR:

And I want to hide the rows like in the below screen shot with no edit link:

By the way, I hide some of edit links, due to using custom module has a hook implements hook_node_access to prevent some users from editing some other user's contents (depending on roles and content ownership)

If you really are using hook_node_access to prevent users from editing those nodes then there's no good solution.  You could implement some Views hooks to hide the results, but then things like pagination are going to be screwed up since pagination is done at query time and it's impossible to write a query that will honor the results of hook_node_access.

If, on the other hand, you're using hook_node_access_records to actually write the node permissions to the database then you can use this Views patch: https://www.drupal.org/node/620392#comment-10222425

The patch will allow you to add a Content Access filter to your view and filter to only show content the user's allowed to edit.


translate interface search exact keyword Is there a way in drupal 7 translate interface to search for exact keyword?
The problem is that when I search for keyword 'no' it gives me 19 pages of results.

No, there isn't any way to do that through admin interface.
The string search is based on the LIKE condition which includes hardcoded placeholders (%) to search for all strings containing your provided string.

Only way for you is to directly tamper with the database or go through all 19 result pages.
Alternatively, you could change the code temporary. For that you have to open locale.inc and go to function _locale_translate_seek() in line 1833. Depending on your search (all, untranslated, translated) you have to look for

->condition('s.source', '%' . db_like($query['string']) . '%', 'LIKE');

and change it to

->condition('s.source', db_like($query['string']), 'LIKE');.

Your search should then only result in exact strings.


Per-item commerce shipping rules working but charging for same item twice I've read similar looking posts, but nothing addresses my particular problem.

I have 2 shipping rates and rules setup and no longer confusing each other (thanks to rfay's excellent vimeo tutorials and the discussion here: https://drupal.org/node/1415638)

One is for domestic and I'm trying to add a 50 cent per item shipping charge to a $3 base.

The other is international and I want it to add a $3 per item shipping charge to an $11 base.

I have things basically setup like rfay documents in https://drupal.org/node/1415638

And it's sort of working. The problem is it appears to be double-counting one of the items - I'm probably saying this wrong.

e.g., 4 domestic items should be base ($3) + 3*50 cents = $4.50, but it is currently computing $5.00

My international rule is behaving in the same way. How do I avoid this double-dipping?

OK - I figured it out. I don't know if this is the best way to do it, but I added an action to my rule, but not as part of the Loop - just beneath it (not indented). This new action is "Subtract an amount from the unit price." For data selector I entered commerce_line_item. For amount, I entered the amount of one additional item (50 for the 50 cents in my domestic shipping example).

So now my rule basically takes the base rate of $3, adds 50 cents for each item including the base item, so then the subtraction action removes that extra 50 cents. Hope this makes sense.


What is the difference between State API vs UserData API? In which case we will use State API ? Instead of UserData API ?

Some Use cases where we will use State API ?

Some use cases where we will UserData API?

Is there any difference apart from the following?

Information stored is not configuration that should be exported.

Real world examples for both. Is any popular contrib or core modules using this concepts(except user module) ?

You find real world examples for State API in the key_value table under the collection state:
comment.maintain_entity_statistics
field.field.deleted
install_time
locale.translation_last_checked
search_api.index.default_index.has_reindexed
system.cron_last
system.maintenance_mode
update.last_check
webform.version

The first part of the name is usually the module. In these examples they are core and the popular contrib modules Search API and Webform.
In contrast UserData API is obviously specific to the user, not the entire system. You would use it for data you don't want to store in a user field. Because it is easy to add user fields in code and config this service is rarely used in Drupal 8+.