Create a view for a specific content(Not for a specific content type!) I have two content types: departments and teachers. Every teacher node has an entity reference field which points to the department to which that teacher belongs.

I want to create a view that shows the list of all teachers from the particular department and I want the link of that view to be shown on the department page. So, each department page will have a link of a view page which will show the list of all teachers from that department.

I can create a view for a content type, but how can I create a view for
a specific node of a content type (e.g Computer Engg department)?

It sounds like you want to put a teacher tab on a node page of type department.

Create a view that shows content (nodes). Filter it to only show teachers. Add a relationship to the department.

Add a contextual filter of nid, and set the relationship (to department) you created on that contextual filter. Hide the view when the filter value is not available, and add validation to it that confirms that it is a node nid belonging to a department.

Add a path to the view: node/%/teachers. Add a menu entry. Set it to menu tab, and give it a title of 'Teachers'.


Make Foo and foo to be different free tagging tags in Drupal 6 I need a way to make Foo and foo to work as two different freetagging words in a Drupal 6 taxonomy field, any suggestions for this?

This goes beyond Drupal - your database is using a case-insensitive collation, so all queries are case-insensitive.

Changing the collation would be the way to sort it ("how" is out of scope here but easy to find on Google), but that might produce unwanted results. I'd advise taking a backup beore making any changes, and having a good read up on the whole collation concept before going any further.

Another approach might be to alter the individual queries that go into the txonomy_term_data table (using hook_query_alter()), and set the collation manually (SQL examples in the COLLATE docs above). Again, your mileage may vary so take a backup before trying anything.


Correct way to add a tweet button? I'm trying to add a tweet button to my node.tpl.php in Drupal 6 - https://dev.twitter.com/docs/tweet-button.

I literally place the html+javascript within node.tpl like so:

Tweet
<

The result is a flickering button every time I refresh, so I'm thinking the javascript is loading incorrectly?

Ideally, I'd like to load the javascript within page.tpl.php, and ensure that it applies to node.tpl, but it doesn't appear to be working. I've also tried loading it using drupal_add_js within template.php various preprocessor methods.

I rather not use any of the social media modules - such as AddToAny, ShareThis, or ServiceLinks - partly because I feel this should be cut and dry w/o module dependency.

So I guess my question is - what is the best way to load that twitter javascript code within node.tpl to avoid the flickering button?

Do not place the <script> tag in node.tpl.php because it will repeat if multiple nodes are arranged to appear in a single page.

Use following code to add js in page and call this function in hook_init() or in your page's callback function.

drupal_add_js('<script>...</script>',array(
  'type' => 'inline',
  'scope' => 'footer'
));


Discard unsaved changes to view in D8 I made a bunch of changes to a D8 view and have not saved it yet. I decided I don't want to go through with these changes and I want to discard all unsaved changes. How do I do this?

You simply need to click on the Cancel button nearby the Save button


Using SQL functions in conditionals in Drupal 7 db_select() I am trying to write a condition into a SQL WHERE clause that forces the column comparison to a variable to be compared in lowercase. However the addExpression function isn't accomplishing this (since that is putting the expression in the field selection, not the where clause.

Here is what I have tried:

$category = 'mobile wifi';
$query = db_select('taxonomy_term_data', 'ttd')
    ->fields('ttd', array('tid'));
$query->innerJoin('taxonomy_vocabulary', 'tv', 'ttd.vid = tv.vid');
$query->addExpression("LOWER(ttd.name) = $category");
$result = $query->condition('machine_name', 'images_cat', '=')
    ->execute()
    ->fetchAssoc();

And this:

$category = 'mobile wifi';
$query = db_select('taxonomy_term_data', 'ttd')
    ->fields('ttd', array('tid'));
$query->innerJoin('taxonomy_vocabulary', 'tv', 'ttd.vid = tv.vid');
$result = $query->condition('machine_name', 'images_cat', '=')
    ->condition('LOWER(ttd.name)', $category, '=')
    ->execute()
    ->fetchAssoc();

The second one becomes invalid and the first one causes the problem I mentioned above. Any thoughts or suggestions?

Thanks,
Patrick

change

$query->addExpression("LOWER(ttd.name) = $category");

to

$query->where('LOWER(ttd.name) = :category', array(':category' => $category));


Character limit of field machine name? Is the machine name of a Drupal 7 field limited to 32 characters (including field_)? When I'm creating a new field, the UI seems to cut me off there, but I wonder if this can be circumvented.

I'm using prefixes to map certain fields to others, and the fact that my prefixed fields are getting cut off is going to make my matching logic slightly more complex.

Yes the length of the field name is hard-coded to 32 characters. It's most likely because the maximum length for a table name in MySQL is 64 characters, and the field API creates tables with names like field_revision_field_name. I imagine the core developers were erring on the side of caution.

It looks like you could squeeze an extra 17 characters out of the field name (64 - 32 - len('field_revision_')), but to do that you'll need to alter the field_config and field_config_instance tables in the database to increase the length of the field_name column (I guess to 49 characters).

I would imagine you'll also need to hook into the field UI forms to increase the #maxlength of appropriate text fields.

It might be easier to re-think your matching logic :)


How can I create a menu item corresponding to a link to another (external) site? In my menu I can create an internal link corresponding to a path like → '/path/to/node'.

But when trying to create a link to an external website (like → http://www.external.com), the link actually becomes → https://www.mywebsite.com/http://www.external.com

So basically, external links are not recognized as external. But instead they get added to the base URL.

How can I make this to work?

You are not allowed to add external link to menu items as this link confirms it too.


Redirect to value from select list I'm having a problem redirecting a user on login. I have a user field field_redirect_field, that is a select list (text).

I want to have a list of links of my site and the user can select in a list where he redirects after logging in. (I create the list manually)

this is an example of my values list:

  user/me/edit|me

The key is user/me/edit and the label is me. Now the problem is in my rule I have a redirect to the field [account:field_redirect_field]. But he redirects to the label and not to the key.

This is what I've tried:

I've tried to change the display of the redirect field by going to Manage Display and set the redirect field to show the Key instead of the label. But the strange thing is that he still shows the value when I want to edit a user.

How can I fix this?

Go to Manage Display, on "CUSTOM DISPLAY SETTINGS" enable the checkbox "Token"


db_update Query Issue I am using ubercart guest checkout module. I am able to submit  the order as guest etc works fine.

After Reviewing the order and submitting it throws me this error

Recoverable fatal error: Argument 2 passed to db_query() must be an array,
string given, called in
/var/www/html/dev.demo.net/sites/all/modules/ubercart_guest_checkout/uc_guest_checkout.module
on line 263 and defined in db_query() (line 2342 of
/var/www/html/dev.demo.net/includes/database/database.inc).

This is the query which is causing that issue

db_query('UPDATE {users} SET name = "%s", mail = "%s" WHERE uid = %d', $name, $mail, $account->uid);

I tried to change this query like this

db_update('users')
->fields(array(
    'name' => $name,
    'mail' => $mail
))
->condition('uid',$account->uid,'=')
->execute();

still no luck, it throws me same above specified error.

How can i resolve the query of above one in order to avoid the error. Any suggestions w.r.t query will be nice.Thanks in advance.

Drupal 7 doesn't use %placeholder style query placeholders. Furthermore, there's an error passing a list of strings to db_query instead of an array.

Your query would be

db_query('UPDATE {users} SET name = :name, mail = :mail WHERE uid = :uid',
           array(':name' => $name, ':mail' => $mail, ':uid' => $account->uid));

However, you should probably use db_update for update queries, in which case it would indeed be:

db_update('users')
->fields(array(
    'name' => $name,
    'mail' => $mail
))
->condition('uid', $account->uid)
->execute();

You error is occurring because the initial db_query accepts an array of parameters in D7.

More info:
https://api.drupal.org/api/drupal/includes%21database%21database.inc/group/database/7


Block layout - List of all blocks I'm having a question about the Block layout in Drupal 8. A couple of months ago (I don't know which beta it was) the block layout looked like this:

As you can see there's a list of blocks at the right of the page. Now in the current beta of Drupal 8 (beta 14) it looks like this:

The list of all blocks is gone. Why did they deleted this? And is there an easy way to get this back?

The same list shows up when you click on Place block. Doesn't look quite the same, but it is.

It was moved because they did UX testing and not a single person managed to place a block in D8, they all completely ignored the right sidebar. So a different solution had to be found, which is currently definitely not very nice yet.

This is the issue: #2513580: Implement the new block layout design to emphasize the primary interaction of placing a block


getFieldDefinitions on Drupal 8 (why all these deprecated functions on DP8?) I don't understand why they are so much functions deprecated on Drupal 8. From the basics (node load, node delete,...) to more complicated (getFieldDefinitions,...).

And their is no explanation for using the new way of implementation in the official documentation.

For example, I want to get the definitions of all my fields for a content type. The old way was :

Drupal::service('entity_field.manager')->getFieldDefinitions(xxx, xxx);

For somes reasons, its now deprecated. Now, we have to use this. But how use it... that's the question. Their absolutely no example or help. I would use the getFieldDefinitions function from this class, but I have to create a instance from it, the function is not static.

How do I do :( ?

Drupal::service('entity_field.manager')->getFieldDefinitions(xxx, xxx);

Is the current way to get field definitions.

It's the EntityManager service that has been deprecated, not EntityFieldManager::getFieldDefinitions. A deprecation notice on a method doesn't apply to the code used within the method, just the use of the method itself.

The former currently proxies straight through to the latter, so it isn't really useful any more.

As a general rule, functions are deprecated when they're no longer useful, or when they break convention with the rest of the codebase. Don't fear it, embrace it. Progress is a good thing :)


Use an existing Drupal site to create a new site Today I tried to copy a existing Drupal site for creating a new one on a other domain-name.

The problem: the new website still uses the old DB. So if I create a new user for example, this user also show up in the other (first) website. The same thing for deleting content.

What did I do:

Created a new DB for the new website.
Backup the DB form the old website and find/replace the domainname
to the new domain-name is the sql-file.
Import the SQL into the new DB
Copy the website-drupal folders from the old website - change the
setting-file in map DEFAULT with the new DB info. (so it connects to
the new DB - after that i FTP the files to the new host.

When I visit the new domain-name a copy of the website showed up and I could login. The first thing I wanted to do was delete all content and users. But seems to be the actions I do in the new website also happens in the old website.

I did a search on Google and find out I did have to change some info in SQL-file. First time I did not do that so I did everything again... so also with step 2)

But the new website seems to be still connecting to the old website. I erased the DB of the new site and the website is still working. So it makes still contact with the OLD DB.

So changing the settings-file and SQL file was not enough.

What did I do wrong??

Any tips, links are welcome!

Hmmmm, you that settings.php should be the ticket, but to really trouble shoot it, it would be easier to see the code. But because that contains your DB connection, that's not something that you should be sharing with others. However, if your having troubles, you could always try going about this a different way.

You could start with a blank db, and toss your settings.php file. That will cause Drupal to think it isn't installed yet, and will take you through the install process. Once your done with that and have a clean Drupal site running on a clean DB, then you can dump your data from your old site into the new DB, which should transfer your data over, but you'll have a fresh settings.php file. That might be easier way to go about it.


Exclude title from display not working I want to hide the titles of the webform by using Exclude form display module.
I installed and given permission for anonymous user to use it. For all webform I am having a common template file that is webform-form.tpl.php. In this template file I am printing the title of the webform like below

print $form['#node']->title;

I thought because of this the module is not working, So i decided to check the checkbox of Exclude title from display is checked or not in this template file. I am not getting exclude_node_title varibale in my template file. So please help me to get this in template file.

I've not gone in detail of the module code, but from brief overview it seems that module doesn't define any variable at template level. You can check if you're able to access $node->exclude_node_title variable in template file. If not, then to hide a node title, you can call _exclude_node_title() function which determine whether the node title should be excluded. Check the example usage of _exclude_node_title() function in _exclude_node_title_preprocess() function.

/**
 * Remove the title from the variables array.
 * NOTE : Example usage from module.
 */
function _exclude_node_title_preprocess(&$vars, $node, $view_mode) {
  // If node title needs to be excluded from display.
  if (_exclude_node_title($node, $view_mode)) {
    $vars['title'] = '';
    if ($view_mode == 'nodeform') {
      // Prevent access to the title field on nodeform view mode.
      $vars['page']['content']['system_main']['title']['#access'] = FALSE;
    }
  }
}


Adding custom meta tags to nodes, dependent on author name? I would like to add the meta tag

`<meta name="robots" content="follow,noindex">`

to all nodes (content type is article) written by specific authors, not only for their new articles but for the few hundred that already exist.

I've installed metatag and metatags-quick, neither seem to offer the functionality I'm after. This is a drupal 7 installation.

I'd rather not have to edit the php, as I'm unfamiliar with that, but I will if I have to.

Does anyone know a way to do this?

I don't know of a metatag module which gives you that level of granularity; you might have to do it in code.

Fortunately, it's pretty easy. You'll need a custom module, in which you should implement hook_node_view(), and use drupal_add_html_head() to add the meta tag based on custom logic.

Very brief example:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'foo' && $view_mode == 'full') {
    if ($node->name == 'admin') {
      $tag = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'name' => 'robots',
          'content' => 'follow,noindex',
        ),
      );
      drupal_add_html_head($tag, 'MYMODULE:robots:noindex');
    }
  }
}


Show fields content node according to its taxonomy using views 3 I need to create a view block type and show only the title of my node and its image but they are related by their taxonomy.

The image is attached to the node.

The node has its taxonomy_field field.

I have two taxonomy vocabularies: products, services.

The block will be placed on pages where have as URL: "taxonomy/term/tid"
But these have their path URL alias, that is: " products/title-taxonomy "
Then, the block is configured to only in scrambled URLs such as " products/* "

When creating my view I have the following configurations:

Fields:
- Title
- field_image

relationships:
- Content: Taxonomy terms on node
- Vocabulary: Products

Contextual Filter:
- Content: Has taxonomy term ID (with depth)
- Provide default value -> Type: Taxonomy Term ID from URL -> Load default filter from term page

But, when I activate the block in the content region does not show me any results.
Change the setting of contextual filter by:

Content: Has taxonomy term ID
Provide default value -> Type: PHP Code -> return arg (2);
This value would only take the url: taxonomy / term / tid that is covered by his alias and would return the tid value.

But I get an empty result. Even in the preview of the view, if I put a value directly, does not generate any results.

What is it I'm doing wrong? Or need some more configuration?

If the title and image you are showing in the block are the same as the title and image of the displayed node, then you do not have to relate the block to the node through taxonomy.

Delete the relationship, and the contextual filter. Set up a contextual filter on Content:NID, and configure it to Provide default value -> Node ID from URL.


drupal 7 error: table blocked_ips not found I have a running Drupal 7 site and wanted to restore it locally on development computer. But on localhost I keep receiving white screen in Firefox or Internal Server Error code 500 on Chrome.

Debugging shows that Drupal is running line 1895 of bootstrap.inc, which says:

$denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();

And just after this line it jumps to error handler, complaining about missing blocked_ips table. The blocked_ips table is not there on either site, the production site had no problem with it.

How to deal with this?

The blocked_ips table is created unconditionally by the system module...it should be there in any standard D7 install.

The process goes like this:

drupal_boostrap() calls drupal_bootstrap_page_cache() when in the DRUPAL_BOOTSTRAP_PAGE_CACHE bootstrap phase.
drupal_bootstrap_page_cache() calls drupal_block_denied()
drupal_block_denied() calls drupal_is_denied()
drupal_is_denied() contains the following line of code:

$denied = (bool) db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();

So Drupal is expecting that table to exist. The only caveat is that if you have a variable called blocked_ips in the variable table the value from there will be used instead of the database being queried. Maybe you have that variable on the local version, and not on the live, and the issue is being masked by that fact?

If you didn't have any data in that table then it would be safe to copy the schema from an empty Drupal install and just create the table.

However, it might be worth checking the integrity of the rest of your data as it sounds like something's gone wrong either on your local copy or during the migration.


how to optimize inline images in ck-editor Is it possible to optimize inline images uploaded via ck-editor.

There is an image with size 11 MB and in default behavior its rendered original without any optimization applied to it.

As you can see in the image below, you only have these settings to optimize your image via upload in CKeditor. Using it you can for sure set the image dimensions, file size and path for images.

The below screenshot is from Drupal 8. You can get the same settings at www.example.com/admin/config/content/formats/manage/full_html


unflag from all users I have created a views list of users who are flagged offensive by other users.

I want a button in front of each user to clear that flag from him from every user. So if admin after checking the user decided that he was wrongly flagged he can simply remove that flag.

I have different view pages for each flag report like following

annoying
offensive
fake

So if I am on view page for list of annoying users, I need a link in front of each user to clear that flag from that user from all/any users.

I'm assuming this question is about D7 ...

Step 1

Start with creating an extremely basic Rules Component with a Rules Action to unflag (using the Flag module) a user, whereas you specify the user to be unflagged as a parameter for that Rules Component. And you pick one of the 3 flags you want to process (eg the "annoying"-flag).

Optionally include whatever Rules Conditions you might need (if any, eg to check if the user is flagged). FYI: this is really like a getting started with Rules ...

Step 2

Use the view of flagged user that you already have and transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?".

In doing so, you'll then be able to use Rules Components (using the Rules module), in which you can then include the required logic to unflag a single user. I.e the Rules Component from Step 1.

Step 3

Use the checkmark in front of each user in your VBO view as the "button in front of each user to clear that flag" (as in your question), and select the custom VBO action that you created in Step 2.

Step 4

Repeat the previous steps for your additional flags, i.e. the "offensive"-flag and the "fake"-flag.


Restrict node to be shown only in a view and not by its url? I created a node which has an entity reference to select a user. Then, I created a view to show the node only to the user referenced in the node.

This works fine, but the problem is that the node can be viewed directly through its URL. I need to restrict the node to be only shown through the view and not by its URL.

How can I do this?

The purpose of the Rabbit Hole module is exactly that, even if it doesn't apply just in the view case.

  Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.

  Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

The module has a version for Drupal 7 and Drupal 8, although the later is still a beta version, on December, 2019.


Content changes history is it possible to view content changes history (author - date) ? We have many users modifying content in our website, and I'd like to know who made each change.

The Revisioning-module is exactly what you are looking for. It keeps revisions of every change and offers you the possibility to moderate the content.
I use it for a few project and I'm very happy with the results!


Unpublished file still downloadable I have a file attached to a node via a link. The node is published but the file is unpublished. The link on the node points to the file /sites/default/files/file.txt

The file is still downloadable by anonymous users.

I would assume the file, being unpublished, would be unavailable to download. This is not the case.

The anonymous permissions are set to view published content.

Is this expected behaviour? What would be the best way to not allow the file to be downloaded once it's unpublished?

You need to setup a private file system in settings.php:

/**
 * Private file path:
 *
 * A local file system path where private files will be stored. This directory
 * must be absolute, outside of the Drupal installation directory and not
 * accessible over the web.
 *
 * Note: Caches need to be cleared when this value is changed to make the
 * private:// stream wrapper available to the system.
 *
 * See https://www.drupal.org/documentation/modules/file for more information
 * about securing private files.
 */
# $settings['file_private_path'] = '';

Files stored in the private file system will be served by Drupal and you can control which users are allowed to access the files.


Error with Node_load() - : Base table or view not found I implemented a function to load nodes which it is loaded from a unitary test..

function labdoo_rest_get_laptop($id) {
    $node = node_load($id);
    return $node;
    }

And i get an error like this:

    Test PDOStatement->execute() failed: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 TabTest PDOStatement->execute() failed: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table                    [error]
&#039;lbd.simpletest291431node_type&#039; doesn&#039;t exist: SELECT nt.*
FROM
{node_type} nt
WHERE  (disabled = :db_condition_placeholder_0)
ORDER BY nt.type ASC; Array
(
    [:db_condition_placeholder_0] =&gt; 0
)
 in _node_types_build() (line 738 of /var/www/lbd/modules/node/node.module).
le                    [error]
    &#039;lbd.simpletest291431node_type&#039; doesn&#039;t exist: SELECT nt.*
    FROM
    {node_type} nt
    WHERE  (disabled = :db_condition_placeholder_0)
    ORDER BY nt.type ASC; Array
    (
        [:db_condition_placeholder_0] =&gt; 0
    )
     in _node_types_build() (line 738 of /var/www/lbd/modules/node/node.module).

The error is difficult to read... anyway i can understand it is trying to load the node from the database 'lbd.simpletest', but it is not correct!!, I don't know why it is trying to do this.... I tried the 'db_set_active' operation, but i receive the same error, also i could get the node information with sql_query but i prefer this method, it seems better.

My file (with name labdoo_rest.test) to test the SQL function is:

<?php

//TODO Add comments

class LabdooRestUnitaryTest extends DrupalUnitTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Labdoo REST test functionality',
      'description' => "Test SQL  operations: Review functions with SQL queries. ",
      'group' => 'Labdoo'
    );
  }

  function testHelloWorld ()  {
        print "test message\n";
        $this->assertTrue(TRUE,"My first test works");
 }
 function testGetLaptop ()  {
        $id=2;
        $result = labdoo_rest_get_laptop($id);
        print "$result"."\n";
        $this->assertTrue(TRUE,"Test get laptop");
}

}

Thanks for your help...

UPDATE:

$id = 2;  <- it is the node's nid, and the node exists
I proved var_dump($node) but I didn't receive results because my error
message is an exception (PDOException).

UPDATE2:

I tested drush php-eval "print print_r(node_load(2), 1)" and it
returns the correct information.
I am using druh with drush test-clean && drush test-run
... to run the function. I suppose the problem is related to the drush test-run call.

UPDATE3:
 - My code in the Github project:
https://github.com/Labdoo/Labdoo-2.0/tree/features/web-services-api/modules/custom/labdoo_rest

Maybe you should define on the test class what profile are you using. Somehow simpletest does not detect it automatically. Without knowing which profile to install, it will not know what is a laptop node, because this content type has not been created. You can try to define on the test class the attribute:

protected $profile = 'labdoo';

See as an example: https://github.com/dashohoxha/oauth2_client/tree/7.x-1.x/tests

In particular, the shell script can be interesting: https://github.com/dashohoxha/oauth2_client/blob/7.x-1.x/tests/run_tests.sh


How to inform future developers about hack in the core? Let's say I had to patch a core of some module, for some reason that doesn't matter here. Is there any custom, or convention of informing future developers about it? So they will be aware of it and this may stop them from updating this module without thinking? Like creating a text file in root directory named "core-hacks" or "important-info-for-maintainers"? I have many ideas but is there any common one? Or if there is not, what would you consider the best? (the last one is open question, so you can discuss in comments).

Added:
I'm considering just creating a directory in root when I will describe what I did and put applied patch, but I'm not sure if this is best what I can do, or if someone may overlook it.

Good question. I know that many Drupal shops have their own rules about documenting patches and hacks, but other than that, I have not seen a convention or standard.

That said, the methods I have seen in various organizations do have some common characteristics. Below are some guidelines that come to mind. Note that these are only meant for non-security patches. If you're fixing a security problem, never store the patch in a publicly accessible place (ie. under your web root) and do not submit the patch in the issue queue but report a security issue instead.

Have a single directory with an understandable name where all patches and their documentation are stored. For instance /patches or /sites/all/patches.
Add the patch file, stored in the patches directory, to your version control system. If you didn't download a patch, but edited some code yourself, create a proper patch file and add it to your version control system.
If you wrote the patch yourself, submit it in the appropriate issue queue on drupal.org so it can be reviewed and committed by the project maintainer.
Create in a text file, eg. /patches/patches.txt, and write down:

What has been patched
Why the patch was needed
A link to the issue on drupal.org where you found the patch (or submitted your own).

When committing all of this to your version control system, write a clear commit message (you always do that, right?) that indicates that you are committing a patch.

IMHO when a developer starts working on a site he didn't build himself, he should always be aware that some code may have been patched. If you use the points above as guidelines your own documentation method, other developers should have no problems in finding out what you patched and why you did that.


Print taxonomy term field in views-view.tpl.php Do you know if it's possible to print a taxonomy term field inside a views-view.tpl.php template in Drupal 7?

For example, you would do this:

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

in node--content-type.tpl.php.

What would be the equivalent to get a specific taxonomy term field in views-view--name-of-view.tpl.php?

Thanks in advance!

For this you need to create the Row style output template file for the view.

For ex: views-view-fields--your_view_name--block.tpl.php.

In this file you get the row array and then you can print your field like:

$row->field_example_field[0]['raw']['value']


Can`t alter views filter option I need to alter my view filter option!

The view must display some comments. Every comment, that I need, has  custom field "node reference". And I want to filter comments by this field.

E.g. if my view displays on page with node 9(nid), view should return me all comments where "node reference" = 9;

I have found such solution: http://www.drupaldump.com/view-3-alter-filters-programmatically

And try to rewrite for me:

function mymodule_views_pre_view(&$view) {

  if ($view->name === 'contest_winners') {
    $view_filters = $view->display_handler->get_option('filters');

    $node_id = arg(1);

    $view_filters['field_for_contest_nid']['value'] = null;
    $view_filters['field_for_contest_nid']['value'][$node_id] = inttostr($node_id);
    $overrides = array();
    $overrides['filters'] = $view_filters;
    foreach ($overrides as $option => $definition) {
      $view->display_handler->override_option($option, $definition);
    }

    dpm($view_filters); // here value = node_id, but view use default value

  }

}

But this does not help: view uses default value.

Maybe i have made some stupid mistake?

It seems you read not complete article :(. before this method getting call we should tell hey views we want use your hooks

something like in your .module file

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

Then create a views directory, create yourmodule..views.inc file there and put your code there ( please be sure your code getting execution with some dsm or die() ).

I know your change your way but I think it help you in another task.

take a look  at : this article


CKEditor placeholder text doesn't work (config.js) I'm trying to add placeholder text to my ckeditor screen like for example Type here ... . You can do this with the configuration helper plugin.

I've placed the ckeditor library in sites/all/libries. I've pasted the plugin in sites/all/libraries/ckeditor/plugins. Then I've added the following code to my config.js (in ckeditor folder).

CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';
    config.extraPlugins='confighelper';
    config.placeholder = 'Type here...';
};

But this doesn't work. The config.js isn't added to my page when there's a ckeditor. The code is also not in ckeditor.js (which is loaded on the page, I thought that the plugin maybe added it to the file).

I've also tried to add the code to my script.js which is always loaded like this:

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.my_custom_behavior = {
      attach: function(context, settings) {
        CKEDITOR.editorConfig = function( config ) {
          // Define changes to default configuration here. For example:
          // config.language = 'fr';
          // config.uiColor = '#AADC6E';
          config.extraPlugins='confighelper';
          config.placeholder = 'Type here...';
        };
      }
    };
})(jQuery, Drupal, this, this.document);

But still no result... . I'm using CKEditor 4.4.2.1567b48 . Text format is filtered html. The ckeditor works but I can't add any plugins (I would also like youtube plugin). Also cleared my cache a couple of times.

Am I doing something wrong?

I'm assuming you are using wysiwyg with ckeditor.

The problem is that wysiwyg pass the configuration to the editor, in our case ckeditor, based on the options selected on the wysiwyg profile in use.

The solution i found sure it's not the best buts works for me. It's about modifying the wysiwyg file thats sets the configuration for ckeditor.

Open site/all/modules/wysiwyg/editors/ckeditor.inc and find the function wysiwyg_ckeditor_settings, then, before the code implode the $extra_plugins array add your extra plugins.

before:

if (!empty($extra_plugins)) {
  $settings['extraPlugins'] = implode(',', $extra_plugins);
}

add:

$extra_plugins[] = 'confighelper';

result:

$extra_plugins[] = 'confighelper';
if (!empty($extra_plugins)) {
  $settings['extraPlugins'] = implode(',', $extra_plugins);
}

Hope it helps.


Publish Content in Drupal by One Editor Only Im a new Admin for an Educational E learning Portal Developed by drupal, the current status of publishing a Content is to be verified or reviewed by two Moderators or Editors. My Question is : How to make (1) Editor publish a content after Reviewing instead of 2?

The Current flow, A "teacher" publish an Educational Content as ( needs review: , then an Editor Reviews that content and then he chooses ONE OF THE FOLLOWING: 1) initial approve 2) send back to Edit " to the teacher" 3) Publish - BUT in order to publish another Editor must review and Publish it to be available as a published content.

the used workflow is the default workbench Flow, But nothing there mentions that 2 Editors must Review,

where can i Find such a code to edit? in which module Block ?

Thank you!

As far as i know, Workbench moderation module works based on user roles. The permission to change the state from needs review to published can be given to one or more roles. It is not possible to give permission to specific person.

In your case:

Create a new state 'Ready to Publish'
Add two state transitions, Needs Review -> Ready to Publish and Ready to Publish -> Published
Make sure you remove the state transition Needs Review -> Published (Or you can revoke the permission for this state transition to editor role)
Create a role called 'Publisher'
Assign this role to second editor
Give state transition permission Needs Review -> Ready to publish to editor role
Give state transition permission Ready to publish -> Published to editor role.

With the above steps, teacher posts the content which will be in needs review state. Editor can review the content and can change the state to 'Ready to Publish'. Now, the second editor who has the role 'Publisher' can review the content and can publish.


Permanent Views Pages Something I've been battling for some time: Is there any way to make the results of a views page permanent?

For Instance: There is a club racing website that inputs Entrants as nodes, to events, which are also nodes. The entrants get scores based upon their performance at the event. However, Entrants come and go in the club, and as they come and go so should their nodes.

Is there any way to make their scores still appear on a views page, even if I happen to delete or unpublish their node? Is there a, 'print as static' option?

The views module actively queries (and caches) a database table for results; trying to make the results static or somehow retrieving deleted content would be much work fighting against views' design. I'd say if you're already using unpublishing to designate former entrants, you're better off using the View Unpublished module to give roles the ability to see unpublished entrants.


jQuery in external file not working I have an external file being loaded via template.php using the following code:

function digital_dots_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if($view->name == 'work') {
    drupal_add_js(drupal_get_path('theme', 'digital_dots') . '/assets/scripts/fx.js');
  }
}

The JS file is being loaded with the following code:

(function ($) {
    $(".image-overlay").hide();
    //alert('It works!');
})( jQuery );

Un-commenting the alert will trigger the alert however the hide effect doesn't?

Very confused!

If you are getting alert from the JS file than it means your JS file is loading properly, and the problem of hide seems to be causing because hide to be called in the document.ready as following:

// Jquery wrapper for drupal to avoid conflicts between libraries.
(function ($) {
  // Jquery onload function.
  $(document).ready(function() {
    $(".image-overlay").hide();
  });
})(jQuery);


Form API ajax add group of users and numbers Im quite a newbe to Drupal, but have made some php.

My problem is that by the help of ajax example pages i've made ajax function to show two fields when checkbox is 1.

When i press the add button i get two more fields, but they are not sortet the way i want to.

The fields are Number and User.

The initial layout when checkbox is checked is:

Number

User

When i press the Add button i get:

Number
Number

User
User

instead of:

Number
User

Number
User

This is my full custom module code:

/*
 * Implements hook_menu().
 */
function test_menu() {
  $items['test'] = array(
    'title' => 'Test functions',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'description' => 'Test functions.',
    'access callback' => TRUE,
  );
  return $items;
}

function test_form($form, &$form_state) {

  $form['#tree'] = TRUE;

  $form['terms3'] = array(
    '#type' => 'checkbox',
    '#title' => t('add users.'),
    '#ajax' => array(
      'callback' => 'test_form_callback',
      'wrapper' => 'options',
      'effect' => 'fade',
    ),
  );

  $form['options'] = array(
    '#title' => t("Generated text fields users and usernumber"),
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'container',
    '#description' => t('This is where we put automatically generated textfields'),
  );

  // Since checkboxes return TRUE or FALSE, we have to check that
  // $form_state has been filled as well as what it contains.
  if (!empty($form_state['values']['terms3']) && $form_state['values']['terms3']) {
      if (empty($form_state['num_names'])) {
        $form_state['num_names'] = 1;
        }
        for ($i = 0; $i < $form_state['num_names']; $i++) {
            $form['options']['number'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('number:'),
            );
            $form['options']['Name'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('Name of user:'),
            );
  }
          $form['options']['add_user'] = array(
            '#type' => 'submit',
            '#value' => t('Add'),
            '#submit' => array('test_form_add_more_add_one'),
            // See the examples in ajax_example.module for more details on the
            // properties of #ajax.
            '#ajax' => array(
              'callback' => 'test_form_callback',
              'wrapper' => 'options',
            ),
          );
          if ($form_state['num_names'] > 1) {
            $form['options']['remove_user'] = array(
              '#type' => 'submit',
              '#value' => t('Remove'),
              '#submit' => array('test_form_add_more_remove_one'),
              '#ajax' => array(
                'callback' => 'test_form_callback',
                'wrapper' => 'options',
              ),
            );
  }
  }

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

  return $form;
}

/**
 * Callback for autotextfields.
 *
 * Selects the piece of the form we want to use as replacement text and returns
 * it as a form (renderable array).
 *
 * @return array
 *   Renderable array (the textfields element)
 */
function test_form_callback($form, $form_state) {
  return $form['options'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function test_form_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function test_form_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

Hope someone can help.

You just have to move the $i value.

Instead of

for ($i = 0; $i < $form_state['num_names']; $i++) {
            $form['options']['number'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('number:'),
            );
            $form['options']['Name'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('Name of user:'),
            );
  }

Use

for ($i = 0; $i < $form_state['num_names']; $i++) {
            $form['options'][$i]['number'] = array(
                '#type' => 'textfield',
                '#title' => t('number:'),
            );
            $form['options'][$i]['Name'] = array(
                '#type' => 'textfield',
                '#title' => t('Name of user:'),
            );
  }


Preprocess function for targeting the home page What's the preprocess function for targeting the home page in a Drupal 8 site? Can I use a preprocess function that is called only for the home page?

To target the front page in a preprocess function you need a condition, because for preprocess you can't use name suggestions:

function mytheme_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    // your code
  }
}


How to trigger Ajax forms machinery I'm working on ajaxifying a form which uses Hierarchical Select widget. I need to update a text field based on the value of HS and a couple of other fields. I want to use Drupal forms Ajax API. I followed the http://drupal.org/node/752056. Now the form is updated when user fills in the text fields. But I can't cope with HS.

I was told http://drupal.org/node/1630186 HS doesn't support regular Drupal #ajax mechanism. I can easily attach the handler to HS update event. So all I need now is to manually trigger Drupal Ajax machinery from my own handler. How it's best to be done?

I see there is a global Drupal.ajax object but can't figure out how to make use of it.

There is a really simple work around for this.
You can add a button or a hidden input field with an ajax callback and trigger this callback by jQuery.

So declare your button:

$form['my_button'] = array(
   '#type' => 'button',
   '#ajax' => array(
     'callback' => 'my_callback',
     'event' => 'hs_changed',
   ),
   // hide the button and set a unique id:
   '#prefix' => "
",
   '#suffix' => "
"
);

In your javascript you can then easily trigger the event with jQuery.trigger:

jQuery("#my_ajax_button input").trigger('hs_changed');

This will trigger your ajax callback.

http://api.jquery.com/trigger/

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax


add a link to admin menu bar I want to add the link to tags i.e. /admin/structure/taxonomy/tags directly to admin menu so that it appears next to "Content" link present on admin menu. How to do it?

You can achieve using below step:

Go to Administration -> Structure -> Menus
Click on 'Add links' in 'Management' menu row
Add 'Menu link title' and 'Path' for menu item.
Set 'Parent link' for the menu item, so it would display in correct position.
Save the form

Update:

By default, Management menu be only dispaly to administrator or the user which has permission to view it.

If you want to set any specific visibility permission, you can use Menu item visibility module.

  This module exposes configurable and extendable visibility settings
  for menu links. For example, if you want to create a 'My account' link
  that points to /user, both anonymous and registered users have access
  to the /user path, so both will see the link, even if anonymous users
  do not technically have an account. Using this module will allow you
  to only have your 'My account' link visible to registered users, and
  hide it from anonymous users.


Subdomain involuntarily redirects to primary domain after logging in or saving I made a development site using development.breinwijzer.be as subdomain. After I've logged in, I'm already back at my primary domain www.breinwijzer.be.

I tried different browsers.
I cleared caches.
I cleared browser caches.
I checked the settings.php file of the development site to see if I have the correct database set for the development site.

Other than this, I'm clueless.

In the settings.php someone uncommented $base_url and put the primary domain of the site as a value. Changing the value into the subdomain I was working in solved the issue.


Can I translate nodes and provide access to their translated content without the use of a site-wide language switcher? Intended behaviour / question

Writer creates /node/5001
Translator translates /node/5001 to french using all the niceties of the Content Translation backend system
Visitor goes to /node/5001 and sees a link in the sidebar to the french version
Visitor arrives at /fr/node/5001, reads it, and then clicks away using one of the main menu links or anything in the sidebar
Visitor is now browsing the website in English, since that's the main language of the website, and the language menu links are written in. The viewing of translated content behaves just like viewing any other page on the website; it doesn't change languages for good.

Things are going wrong between steps 4 and 5, since step 4 puts the website in "French mode" which means all menu links point to french versions of content. In theory, all subsequent browsing will be in French (which is not what I want), and in practice the language will switch back and forth between French and English depending on the availability of translations (which is even worse), even though the URL will include the /fr/ prefix no matter what is actually displayed.

Is there a practical solution to this?

Background / supplemental

I've enabled Drupal 8's Content Translation and Language modules. Language detection & selection is done using the default mechanism, which recognizes language code prefixes in the first component of the website's path (for example, /fr/node/1, for the french version of node 1).

I'm now wondering if there's any way, without going toe to toe in a fight to the death with the Drupal final boss, to provide translations ONLY of the content on select pages, but NOT of the entire site, such that the content is made available through links on my website, with the default language being restored to English when navigating away from those same pages?

The intention is to use Drupal's built-in (though other non-core suggestions are welcome) translation management features to create and manage subordinate multilingual content on the backend, but then access these translations on a case by case basis through links in a block for example, without having these navigation actions trigger persistent language selection events (from a user perspective) which rewrite all the menu URLs to match.

Basically, I'm trying to get something to work that would be the Content Translation module equivalent of a bunch of multilingual PDFs attached to a single piece of English content. Except I don't want to link to PDFs, I want to link to ordinary web pages, with the only real difference being that they're written in another language, and linked to an English version behind the scenes.

Am I wasting my time with this, or is there a way to translate just a subset of my content, with access opened up to those translations from the english site, minus the persistence of a full-on language switch for the remainder of the browsing session?

A simple solution in such cases would be to remove the language switcher and provide for translated content only modal links:

French version

You could add the links to the node, in a template or preprocess hook. Or create a block (View or custom block plugin), which lists the available translations of the current node as modal links.

How to build such links see How to open a popup form from a view link?


User generated review site where users are matched when they review products similarly On my site users will be able to give a 1 to 5 rating for various different products. I want to show users other users that have rated products in a similar way.

So in simplistic terms, if the followong users rated a prodcut like so:

User A - 5 stars
User B - 4 stars
User C - 1 stars
User D - 0 stars

Then User A and User B would be matched, and User C and User D would also be matched.

How sophisticated an algorithm is achievable with only drupal modules and minimal php? Ideally a point system would find the similarity / difference between users’ ratings for all the products that they have both rated, and then find the top 5 closest matches and rank them accordingly.
Thanks

This should be achievable using some combination of Flag, Fivestar, and Views. You can use Views to find users that match criteria based on the current user. You shouldn't need any PHP, in theory at least.


How should I render the tpl of module at theme I create a module and mymodule.module file like this:

function mymodule_menu(){
    $items['mymodule/list']=array(
        'type'=>MENU_CALLBACK,
        'page callback'=>'mymodule_list_view',
    );
    return $items;
}

function mymodule_list_view(){
    theme('list_view');
}

function mymodule_theme($existing, $type, $theme, $path){
    return array(
        'list_view'=>array(
            'template'=>'mymodule_list',
            'type'=>'theme_engins',
        ),
    );
}

then I create templates file: mymodule_list.tpl.php

And I create a theme and create templates file: page--mymodule.tpl.php. Now when I access /mymodule/list, it will use page--mymodule.tpl.php to render the page.

My question is: how should I write page--mymodule.tpl.php to display the content in mymodule_list.tpl.php?

You don't need a customized page template file because you are using a template file for your theme. What you need to do is to fix your code, which should be as the following one.

function mymodule_menu() {
  $items['mymodule/list'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'mymodule_list_view',
    'access arguments' => array('access content'),
  );

  return $items;
}

function mymodule_list_view() {
  return theme('list_view');
}

function mymodule_theme() {
  return array(
    'list_view' => array(
      'template' => 'list-view',
    ),
  );
}

Notice that:

For the menu callback, you should define the access callback, and the access arguments, or the menu will not be visible to the users (except the user #1). By default, Drupal uses user_access() as access callback; in this case, you need to provide the permission string as access arguments.
The template filename must be equal to the theme name; the only acceptable difference is the underscores replaced by hyphens.
Your page callback needs to return its output, or print it. In the first case, the rendered page will contain all the output returned from Drupal, such as blocks; in the second case, the rendered page will just contain what your page callback prints.


Looking for database insert example According to db_insert manual page this function is deprecated and it is better to use Drupal 8 database connection to perform insert.

  Deprecated

  as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a
  database connection injected into your service from the container and
  call insert() on it. For example, $injected_database->insert($table,
  $options);

Now how can I get a database connection and call insert() method?

To inject the database service add/alter the following methods in your controller class:

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;

class PetmdController extends ControllerBase {

  protected $database;

  public function __construct(Connection $database) {
    $this->database = $database;
  }

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

  public function foo() {
    $this->database->insert(...)->fields(...)->execute();
  }
}


Custom block template All the examples for creating custom block online return #markup from build(), but I'd like to return a render array and have it use a template that's part of the module.

Would love an example of how to do this.

An array with #markup is a render array, just the most basic version of it. If you want to use a theme or template, then just do so. Using and defining templates hasn't changed that much compared to D7, the biggest difference is that they're now html.twig files and not .tpl.php.


How to update a module's view programmatically using hook_update_n? We're writing some update functions for a custom module. This custom module provides some views:

/**
 * Implements hook_views_default_views().
 */
function mymodule_views_default_views() {
  $views_dir = drupal_get_path('module', 'mymodule') . '/views';
  $views_files = scandir($views_dir);
  $views = array();
  foreach ($views_files as $filename) {
    if (substr($filename, -4) == '.inc') {
      include_once $views_dir . '/' . $filename;
    }
  }
  return $views;
}

There are several .inc files from the view export ui and all those views are provided.

Now: some of those views should be updated. We usually just export and re-import them using the view ui (and override existing views). We wondered, how would this be possible programmatically? How to tell views which files to import again and override?

function mmodule_update_7001() {
  // what goes here?
}

Thanks for any ideas!

we ended up adding the following code inside the update_n function:

  $views_dir = drupal_get_path('module', 'mymodule') . '/views';
  $views_files = scandir($views_dir);
  $views = array();
  foreach ($views_files as $filename) {
    if (substr($filename, -4) == '.inc') {
      include_once $views_dir . '/' . $filename;
      if (isset($view) && is_object($view)) {
        views_save_view($view);
      }
    }
  }


Specific localization server for a module Hello fellow Drupal developers...

When installing a new language, the Localization Update module downloads the necessary (.po) files from Drupal's localization server.  However, is there a way to specify where a module should download this from?

This shouldn't be for ALL of the modules, but only a package of modules or just one single module.

Is there a hook, or some sort of info configuration we can place in the module's .info file?

You can specify an alternative source for translations in .info file in different ways:

l10n server = http://example.com

l10n url = http://example.com/path/to/l10n_server.xml

l10n path = http://example.com/path/to/%core/%project/%project-%release.%language.po

If your localization server is based in l10n_server module, l10n server is enough.

If you're not using l10n_server but a custom solution, you may want to provide l10n url key with the url to a custom-build xml file to inform l10n_update about where to get translation updates from.

Lastly, if you're not using l10n_update and you're not planning to generate such an update xml file, you can pass the path to the .po file with l10n path, you can use some placeholders in this path, as shown above.

For more information, see l10n_update's README.txt and docstrings for l10n_update_build_projects().


How to limit access to a meeting content type to only the participants specified via Entity Reference? I have a content type that contains information about meetings. One field of this content type is 'members', which is of type Entity reference (a field type provided by the Entity Reference module). It specifies the included users in the meeting (using a multiple select list).

I want the content to be accessible only by these specified users.

Is it right to use the Node access user reference module for this purpose? If so how?

Use the Node access user reference module. Since you're already using Entity reference, it should fit. Some more details about this module (from its project page):

Gives content access permissions to users for content that references the users with User reference or Entity reference.
This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

You should configure the module similar to the settings shown in the screenshot on its project page, which is like so:

Though I would uncheck the Grant for all users option (= view).
That way the users who can create such meetings (nodes) have all permissions they need (since they'll be the author). And the "specified users" will be able to view it, which appears to be exactly what you want.
To actually configure these settings, refer to the module's README.txt, which includes these instructions:

Create a field to reference users in a content type using the Field UI.  The field's configuration page will contain the settings for Node access user reference. For detailed instructions on using the Field UI see:
https://www.drupal.org/documentation/modules/field-ui


How to export users with passwords? How to export users with passwords?
The Users export module cannot help, it export without passwords.

User passwords are stored using a one-way hashing algorithm and cannot be converted to plaintext.  In addition, each Drupal site uses a unique cryptographic salt, so that the same plaintext password on two Drupal sites will not result in the same hashed password.

In other words, there is no way to generate a list of usernames and plaintext passwords.


How to use field_groups in admin only? I want to use field_groups in my content type to make it easier to deal with a long content type, but I don't want that group (probably a fieldset) to be rendered at all on the client-facing side.

How do I control that?

Use CSS to change the div created by the field group.  Set margin, padding, border and font-size to 0.

Don't hide the div because that will hide the contents of the div.


Running check_plain after t Will this be correct :

drupal_set_title(check_plain(t("Donation Details for Project: $project->title")))

I want all of the string to be translated when needed. Should call check_plain first then t or vice versa?

This would be better:

  drupal_set_title(t("Donation Details for Project: @title"),
  array('@title' => $project->title));

Taken from here

  Special variables called "placeholders" are used to signal dynamic
  information in a string which should not be translated. Placeholders
  can also be used for text that may change from time to time (such as
  link paths) to be changed without requiring updates to translations.

  @variable, which indicates that the text should be run through
  check_plain, to escape HTML characters. Use this for any output that's
  displayed within a Drupal page.


Views Data Export: Export to XLS with column labels? The fields gets exported to XLS, but no labels are generated for every field, but missing field labels. Labels are set for every field in the field option.

Should be:

Field Label 1 | Field Label 2 | etc.
====================================
Data 1        | Data 2        | etc

But now it's just fields with no column labels

====================================
Data 1        | Data 2        | etc

Is it a setting I'm missing out in Views or tpl.php templates needs editing?

If your spreadsheet is missing the field labels as column headers, chances are the "label" setting is disabled on each field (probably because, you have another display in the view with the labels turned off).

For each field in the Fields section,

Click the field name to open the settings option.
If necessary, be sure to choose For "This views_data_export (override)" from the top of the modal.
Enable the checkbox to Create a label and set the column heading/field label for the spreadsheet.
Click the Apply (this display) button at the bottom of the modal to save the settings for that field.

Save the view, clear your caches, and test the export again.

If the labels are set, the next course of action to check include:

Checking for any template files either in the theme or a custom module that could be overriding the settings.

Within the view, you can click the Information link next to Theme at  the bottom of the Advanced section (far right of views edit screen). It will list template filenames that could override the view,  and render existing templates in bold.
Should you find a template outside of the Views Data Export module's folder, you can temporarily remove it and test to see if it resolves the export issue.

Checking to make sure you are running the most up-to-date version of the module.


Reordering vertical tabs Is it possible to reorder vertical tabs in the node edit page?  There are certain buried tabs that I am constantly needing to switch to, and it would make my life much easier (and that of my users!) if I could change the order to put the frequently used tab on top.

Note regarding similar questions:
I realize something similar has been asked, but he asked specifically about doing it by weight, and I'd be happy with any method of reordering them, in case there are other ways.  And no one answered his question, which leads me to hope there is some other way to do it.  If there's no way to do this at all, then I'll either delete this question--if that's the general consensus of the community--or accept the answer that it's not possible, as long as it is convincing and no one disputes it.

Reading between the lines of the other mentioned question and its comments and answer, I've been able to pull out these useful bits of information.

You can do this with
hook_form_FORM_ID_alter
You can find the correct FORM_ID by looking at the HTML source of the form you're working with.  It's given inside the  tag.   Apparently you need to replace the hyphens with underscores.
The code might include something like this:

function hook_form_sublanding_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['promotion_settings'] = array(
    // something goes here....
  );
}

The code is very incomplete and quite possibly incorrect.  Perhaps someone will complete/correct it.


how to import from csv file to EntityForm I have two drupal sites with exactly same entity forms, I would like to import entityform submissions from site A to entityform submissions site B.

I had a look into feed modules which works very well to import node but there is no option for to import data into entityform.

There doesn't seem to be any contributed module available for importing Entityform submissions from CSV.

You can simply try creating a small module which read CSV data and import Entityform submissions. To do this you can simply write a batch operation using Batch API and create Entityform Submissions using code snippet available here.

Another way could be to try Bundle Copy module that works with major entity in Drupal Core and also provide simple API for new/custom Entities. I've not tried Bundle Copy with Entities other than Node. You can try if this works with Entityform if not you can use its API and extend it.


Menu management options in Drupal 7 On node add/edit form, when the navigation menu grows, it becomes harder to find the menu parent in which we want to add the node link. Is there any module through which it becomes little easier?

Secondly, on the menu management page where it displays all the menu items, is it possible to drag multiple menu items? Is there any menu management module like the Taxonomy manager module?

Hierarchical Select - with "hs_menu" submodule this module allow built "hierarchical" select of parent for menu.


Contextual Filter with Title and Language I'm building an api that is going to change base on the title and the language that is been request. This request is base on the URL something like this www.example.com/abc/fr-fr

abc = title of the content
fr-fr = Language Code name

For some reason the context filter of the language is turning my search into empty. Here is what happen when I try to run www.example.com/abc/fr-fr

{
  "nodes" : []
}

And it should looks like this instead:

{
  "nodes" : [
    {
      "node" : {
        "Literal Api" : "{\n \"glossary\": {\n \"title\": \"example glossary\",\n\t\t\"GlossDiv\": {\n \"title\": \"S\",\n\t\t\t\"GlossList\": {\n \"GlossEntry\": {\n \"ID\": \"SGML\",\n\t\t\t\t\t\"SortAs\": \"SGML\",\n\t\t\t\t\t\"GlossTerm\": \"Standard Generalized Markup Language\",\n\t\t\t\t\t\"Acronym\": \"SGML\",\n\t\t\t\t\t\"Abbrev\": \"ISO 8879:1986\",\n\t\t\t\t\t\"GlossDef\": {\n \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n\t\t\t\t\t\t\"GlossSeeAlso\": [\"GML\", \"XML\"]\n },\n\t\t\t\t\t\"GlossSee\": \"markup\"\n }\n }\n }\n }\n}",
        "Title" : "abc",
        "Language" : "French"
      }
    }
  ]
}

Things that I have already try it out:

I thought that the problem was having multiple contextual filters
but that did not fix the problem because I try using it only the
language contextual filter and I still have the same problem.
Also, I try to use the word "French" instead of the language
code, which is "fr-fr" and this did not fix the problem.

Here is my view configuration:

Note I'm using node translation in 7, not entity/field translation. Each language has its own copy of a node.

My question is why I'm getting an empty node instead of the entire node information?

Multiple contextual filters are fine & dandy.
The issue seems to be that the url prefix being used in a translated/localized content is a bit different from the actual machine code for the language. French is not 'fr-fr' but simply 'fr' in Drupal's views. French Canadian would be 'fr-ca'.

here is a list of defined languages I use on my site along with their codes. These should be what you're looking to filter on. No issues with multiple filters.


Aren't the Article content type and the Blog module the same? Here's a small question, if Drupal already has an Article Content Type, what then is the use of the blog module? Aren't they supposed to be the same?

The blog module allows several users to have different blogs. It adds more features that are typically found in a blog to the article. If you are making a single author blog it might be better to build with Views using the Article content type than use the blog module.


Displaying top visited links from other content types in one (filtering) I have made one block for most visited links (Top Links) in my Drupal website, but I don't know how to list most visited from different pages. For example, if I have created a page named "Drupal" and within that page I have added some content with some title, then I have to examine and count those titles and list the top visited title from each and every page on my homepage (only one from each and every title that is most visited) and list them on my homepage block.

Could anyone help me with this.

If you want to use views check this answer.

There is Drupal Most Popular module

  Showcase the most popular content across your Drupal website and
  engage your audience.

Documentation

Also there is Radioactivity module.

  This module provides a field type which can be used as a hotness
  metric or a regular view counter for entities and for much much more.
  In essense, entities receiving attention (views or actions defined by
  Rules) are heated while inactive ones slowly cool down.


Store a field on a node I altered the node form and added an manage_file-field; then, I added a callback on the #entity_builders property.

$fid = $form_state->getValue('file')[0];
$file = File::load($fid);

$file->setPermanent();
$file->save();

// $node->set('field_file', $file);
$node->field_file->setValue([
  'target_id' => $file->id(),
]);

However this gives me the following error:

  The file used in the File field may not be referenced.

At this point, I cannot use file_usage, since the node is not yet saved.

How can I solve this?

Set the status of the created file to something other than PERMANENT.

So replace

$file->setPermanent();

with

$file->status = 0;

The file field will then set the status to permanent and add the file_usage metadata.


TinyMCE not appearing on custom form I am creating a custom form and have run into a problem. I'm using the WYSIWYG module and for some reason the text areas  on this custom form don't show as rich text editors (tinymce shows on other parts of he site)

    $form['terms_format'][implode('~', array(MODULE_NAME, FIELD_TERMS))] = array(
    '#title'         => t('Terms and Conditions')
   ,'#type'          => 'textarea'
   ,'#description'   => t('Terms and conditiona')
   ,'#default_value' => variable_get(implode('~', array(MODULE_NAME, FIELD_TERMS)), "")
   ,'#required'      => TRUE
);
$form['terms_format']['format'] = filter_form(FILTER_FORMAT_DEFAULT);

Any ideas what i'm doing wrong? I'm using drupal 6.

you need to specify the format value 'format' => 'filtered_html' to allow filtered html or '#format' => 'full_html'

$form['terms_format'][implode('~', array(MODULE_NAME, FIELD_TERMS))] = array(
    '#title'         => t('Terms and Conditions')
   ,'#type'          => 'textarea'
   ,'#description'   => t('Terms and conditiona')
   ,'#default_value' => variable_get(implode('~', array(MODULE_NAME, FIELD_TERMS)), "")
   ,'#required'      => TRUE
   'format' => 'filtered_html',
);

For drupal 6 try

if (!isset($edit['format'])) {
  $edit['format'] = FILTER_FORMAT_DEFAULT;
}
$form['terms_format']['format'] = filter_form($edit['format']);

Make sure your default filter format is filtered html or full html


I get the following error message while updating a Drupal site I keep getting this error when I try to update Drupal. I have no clue what it means; it seems I have a missing column.

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.access_exposed' in 'field list':
  SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.status IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2)) ; Array ( [:db_condition_placeholder_0] => 3 [:db_condition_placeholder_1] => 2 [:db_condition_placeholder_2] => 6 ) in EntityAPIController->query() (line 152 of /opt/readyby21.org/public_html/sites/all/modules/contrib/entity/includes/entity.controller.inc).

According to http://drupal.org/node/1489394 some users experienced this problem when updating their rules module.  It looks like you'll need to update your rules, entity and internationalization modules all need to be updated to the latest versions (7.x-1.5 for internationalization and 7.x-1.0-rc2 for entities).  If you already have, try only updating those modules, before attempting to update the rules module (you can disable the rules module.  This should also solve the problem, but I assume you're using it for something or other).

As BetaRide points out above, checking into your web logs may shed some additional light on the problem, in case the above doesn't solve the problem.


Set up login to open a specific view I created a page view where user only get articles to edit.

How can I set up the page that it opened when a user logged in?

You are looking for functionality that is available in some ready modules. Login Destination looks like a solid bet:

  The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them.

Seems to be exactly what you need.


Twig template for search results page I'm attempting to create a custom template for the search page located at

127.0.0.1/search/node

I've created a template called search-result.html.twig in my theme/templates folder which allows me to modify each search result but I'd like to actually modify the buttons and text fields at the top of the search page.

Is there a specific template that affects the search button and fields?

but I'd like to actually modify the buttons and text fields at the top
  of the search page.

They do not have templates by default, because they are forms. You could create a twig template for the search form by follow this tutorial: How to manipulate forms in Drupal 8

But in my opinion, it is easier to use hook_form_alter on your .theme file and add the classes here.

This is how, the drupal default theme, Bartik changes the search button to a magnifying glass icon by adding a custom class to the submit button in bartik.theme

/**
 * Implements hook_form_alter() to add classes to the search form.
 */
function bartik_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, ['search_block_form', 'search_form'])) {
    $key = ($form_id == 'search_block_form') ? 'actions' : 'basic';
    if (!isset($form[$key]['submit']['#attributes'])) {
      $form[$key]['submit']['#attributes'] = new Attribute();
    }
    $form[$key]['submit']['#attributes']->addClass('search-form__submit');
  }
}

You can use Devel and use dpm($form) to see what's inside the $form array.

Example:

/**
 * Implements hook_form_alter() to add classes to the search form.
 */
function bartik_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, ['search_block_form', 'search_form'])) {
    $key = ($form_id == 'search_block_form') ? 'actions' : 'basic';
        drupal_set_message(dpm($form));
  }
}

Make sure you don't have the search block on the search page, other wise it will print the array for both forms and might confuse you which one is which.


Add product(s) to cart from DOM string short version:

how can I add multiple items to a cart from a served string that provides the product ids and their quantities? I suppose a rule could handle this somehow?

long explanation:

hey guys,

I'm trying to make some bigger changes to the add-to-cart form and the way it functions, for my client and I have specific needs here.
Usually the form only let's you add one type of product variation at a time, but I want visitors to be able to set multiple product variations of the same product node, and the 'Submit' button submits all of them, instead of just the currently selected variation.

To put this into perspective: Let's say I have a product (display node) called

Brick

This Brick holds three variations:

Brick (Front) , Brick (Side) , Brick (Top)

Using a Custom Line Item, it gets these options added automatically (taxonomy term list reference):

Red , Green , Blue

Here, we want users to be able to (for example) click Side and select Green, then hit Front and choose Red, and when they hit Submit, both of these get added to their cart. By default however, of course only one - the last selection - is added.

Now, using a hook_form_commerce_cart_add_to_cart_form_alter() and custom JavaScript, I've gotten to a point where my JS automatically stores the entire selection inside a JS Object. But from hereon, I'll need your help guys.

I can easily print the JS Object into the DOM as a string with a format such as VariationID:LineItemOption:Quantity[_repeat].
For example the string could read 31:2:1_32:3:1 (which for humans would read Side:Green:1, Front:Red:1).

From hereon, though, I dont really know how to progress. My idea would be to perhaps create a custom rule that (replacing the action of the default Submit button) receives that string, filters it and adds matching items to the cart.

Really hope someone here has an idea on how I could progress. Any suggestion and recommendation would be highly appreciated!

If I understood you right. I had some similar task in the past. I had form of all product variations in the table with textbox inputs for quantity. And they must be added multiple to cart.

The main function is commerce_cart_product_add_by_id($product_id, $quantity);

What I did:
I created custom field formatter for "Product reference" field and rendered it as table of variations with text inputs for quantity.
And on form submit I loop all products in foreach and add them to cart.

But if you don't want to create additional formatters there is another solution.

You can use your hook hook_form_commerce_cart_add_to_cart_form_alter()
Render form elements for all your product variations there by custom code.
Replace form submit with your custom submit
Add products to cart in custom submit (call commerce_cart_product_add_by_id() in foreach).

Also you can write your text VariationID:LineItemOption:Quantity[_repeat] into some hidden textfield element. After submit you'll read this text in $form_state


Why are some images not displaying after migration to localhost? I just moved a site from a production environment to an ubuntu based localhost set up and some of the images aren't displaying and are popping up in the console as 404 errors.

The files are present on the localhost set up, and they have the same permissions as the images that do show up. I think this means that the files are corrupted. So,

How do I test/fix this?
How can I prevent this from happening in the future?

So, I'm my case the files were getting corrupted durring transfer via ftp. Archiving the files first and then transferring the archive solved the problem.


How can I stop a message (displayed via drupal_set_message()) from being printed? When a node is saved, the Location Taxonomize module by default prints a message if terms are created.  This message is very confusing for my users so I want to remove it.

I found where the message is being displayed in the module's code:

/**
 * @param $items - an array of items ready to be taxonomized
 */
function location_taxonomize_taxonomize($items, $form, &$form_state) {
  $saved = 0;
  $tids = array();
  foreach ($items as $item) {
    $results = location_taxonomize_process_item($item);
    $saved += $results['saved'];
    $tids = array_merge($tids, $results['tids']);
  }
  if (!empty($tids)) {
    if (location_taxonomize_term_attach_enabled()) {
      location_taxonomize_term_attach($tids, $form, $form_state);
    }
  }
  $msg = t('Location taxonomize: @num new terms saved', array('@num' => $saved));
  drupal_set_message($msg);
  return array("saved" => $saved, "tids" => $tids);
}

Obviously I could just delete the line drupal_set_message($msg); but then I would have to do this every update and I would eventually forget.  I'm still learning how to use hooks and I know that hooks can be used to remove form elements but what about status messages?  Is it possible to stop the message from being displayed using hooks and if so, could you please give me some pointers about how to go about doing so?

I admit to not having used it before but the Disable Messages module looks like it would do the trick:

  Gives a site owner options to disable specific messages shown to end users.

  Features:

  Filter out messages that match a full text string exactly.
  Filter out messages that match a regular expression.
  Permissions to specifically hide all messages of a given type from any role.
  Disable all filtering for specific users.
  Disable all filtering for specific paths.
  Apply filtering only for specific paths.
  Debug system to get messages in the HTML without showing it to the end users.

I think a regular expression would probably be best for this particular message (because of the replacement done using t()); something like this should work:

^Location taxonomize: [0-9]+ new terms saved$


What is the "right" way to track a custom patch to a contributed module? I need to apply this patch to my site:
http://drupal.org/node/483176#comment-5939648

What is the "right" or "responsible" way to track this change? We use Git for version control.

I keep all of those in the projects make file, which makes it easy to apply the patch again should the module be updated without it commited, and remove it when it's no longer necessary.

This answer makes the most sense in context of my answer to the question Should I source control contribed modules in my project?.


Drupal 6 views and duplicates I have view that shows articles. It works fine if user selects one image but if she selects multiple images to article, it will duplicate the article on my view X amount time (x = number of images that article has). I have tried using distinct but that doesn't do any difference. Why would this image amount effect on this?

I'm using Drupal 6, with Views Version 3.

Here is the query if it helps:

 SELECT DISTINCT(node.nid) AS nid_1, users.uid AS users_uid,
 node_data_field_article_image.field_article_image_fid AS
 node_data_field_article_image_field_article_image_fid,
 node_data_field_article_image.field_article_image_list AS
 node_data_field_article_image_field_article_image_list,
 node_data_field_article_image.field_article_image_data AS
 node_data_field_article_image_field_article_image_data,
 node_data_field_article_image.delta AS node_data_field_article_image_delta,
 node.type AS node_type, node.nid AS nid, node.vid AS node_vid,
 node_data_field_article_color.field_article_color_value AS
 node_data_field_article_color_field_article_color_value,
 node_data_field_article_numbers.field_article_numbers_value AS
 node_data_field_article_numbers_field_article_numbers_value, node.created AS
 node_created, users.name AS users_name, node.title AS node_title,
 node_revisions.body AS node_revisions_body, node_revisions.format AS
 node_revisions_format, feeds_node_item.url AS feeds_node_item_url FROM node node
 INNER JOIN users users ON node.uid = users.uid LEFT JOIN
 content_field_article_image node_data_field_article_image ON node.vid =
 node_data_field_article_image.vid LEFT JOIN content_type_blog
 node_data_field_article_color ON node.vid = node_data_field_article_color.vid LEFT
 JOIN content_field_article_numbers node_data_field_article_numbers ON
 node.vid =
 node_data_field_blog_font.vid LEFT JOIN node_revisions node_revisions ON
 node.vid = node_revisions.vid LEFT JOIN feeds_node_item feeds_node_item ON
 node.nid = feeds_node_item.nid WHERE (node.type in ('blog', 'feed_item')) AND
 (node.status = 1) ORDER BY node_created DESC

The version you have should provide an option for the image field Group multiple values and also underneath this you can choose just to show 1 image. Either or a combination should stop these duplicates happening


Libraries in custom module I have the following 2 files in 2 different directoties in a custom module directory.

modules/custom/calculator

This is my info.yml file (calculator.info.yml)

name: calculator
type: module
description: Calculator
core: 8.x
package: Custom

My css is in  the directory modules/custom/calculator/css and js in the modules/custom/calculator/js directory

My libaries file is this: (calculator.libraries.yml)

base-style:
  version: VERSION
  css:
    component:
      css/wunderpage.css: {}
  js:
    js/wunderpage.js: {}
    js/jquery.matchHeight-min.js: {}

I also have a calculator.module file :

<?php

/**
 * @file
 * Contains calculator.module..
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function calculator_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the calculator module.
    case 'help.page.calculator':
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('Calculator') . '
';
      return $output;

    default:
  }

  function calculator_preprocess_page(&$variables) {
    $variables['#attached']['library'][] = 'calculator/base-style';
  }
}

Still my css and js etc is not being loaded.

Somebody knows why my libraries are not being loaded?

Either you made a mistake when copying and pasting that PHP code, or you defined calculator_preprocess_page() as being inside calculator_help(). Also, as Ivan Jaros also pointed out, Drupal 8 requires you to use hook_page_attachments() to attach page-level assets.

I do recommend you add these assets elsewhere in the code, preferably in the render array you build that actually needs the library.


Admin menu sometimes doesn't show up I'm having some strange issues with the Drupal admin menu system. I can't reproduce it reliably, but these are the steps that usually cause the problem:

Go to /user and log in. This works as expected and redirects me to the user page, where I see the admin menu.
Navigate to the front page, either by clicking a link on the page or by manually entering the / address.
Observe that there is no admin menu.
Refresh the home page (possibly a couple of times), and the admin menu may eventually appear.

I've tried both Firefox and Chrome in private browsing sessions, as well as clearing the Drupal admin menu cache. I'm completely thrown by this, as checking in Firebug/Chrome developer tools reveals the SESSxxxx cookie properly set and not changing between when the menu is shown and when it isn't.

Related questions refer to CSS/JS aggregation issues as well as permissions errors. It seems unlikely that at least the latter problem would be so unreliable.

I have Drupal 7 running on PHP 5.4.39/Apache 2.2.22 under Debian wheezy.

The few times i have had a similar issue i have resolved it by turning off 'Cache menu in client-side browser' on this page admin/config/administration/admin_menu


Modify HTML Output of A View? So I have setup a View as a Block that echoes out three products from Commerce. However I want each of the items to be formatted in this way:

PRODUCT PRICE

PRODUCT DESCRIPTION

Donate Now >

Is it possible to edit the formatting specifically in this way?

Thanks for your time!

You can make the same with semantic views, it let you to choose what hmtl tag wants for every field, and also what class/id you want to use.

also, without programing,

I leave enable the link.

I dont't output the amount.

But in the 3º element, I will rewrite the ouput and add the [amount-token] So you can build the div you need also.

all this without use tpl.

anyway the best option always will be to make make as say the first comment.


Ckeditor not applying to textarea I have a textarea field in a custom module form , I guess there is ckeditor library by default in core in d8 . I tried the following :

$form['fieldset']['email_template'] = array(
  '#type' => 'text_format',
  '#format' => 'full_html',
  '#title' => t('E-mail template content'),
  '#default_value' => "

" . $dvalue,
  '#description' => t('A valid template for email trigger. Please type ":" for variable suggestions'),
  '#attributes' => array(
                ),
  '#required' => TRUE,
  '#cols' => 60,
  '#resizable' => TRUE,
  '#rows' => 13,
  //'#wysiwyg' => TRUE,
            );

I followed the link : https://www.drupal.org/node/1031160

But the ckeditor is not applying to the textarea as expected . Any idea ??

UPDATE

I was not given the text_format as ckeditor in https://base_url/admin/config/content/formats .

I defined a new format which can apply to which all fields needed as ckeditor . cheers

Go to /admin/config/content/formats and check the CKeditor is enabled for FULL HTML. Also, could be a role issue, by default Full HTML is for admins only.

Important:
For safety/security reasons FULL HTML should be used by admins only. You're better off using basic_html as your format if this form is for authenticated or anonymous users. You may need to adjust the roles so anonymous can use it.


Access denied while deleting an entity This is my Config entity:

 * @ConfigEntityType(
 *   id = "myentity",
 *   label = @Translation("My Entity"),
 *   controllers = {
 *     "storage" = "Drupal\Core\Config\Entity\ConfigEntityStorage",
 *     "list_builder" = "Drupal\mymodule\Controller\MyEntityListBuilder",
 *     "form" = {
 *       "default" = "Drupal\mymodule\Form\MyEntityForm",
 *       "delete" = "Drupal\mymodule\Form\MyEntityDeleteForm",
 *     },
 *   },
 *   admin_permission = "administer mymodule",
 *   config_prefix = "myentity",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "url" = "url",
 *     "status" = "status"
 *   },
 *   links = {
 *     "canonical" = "mymodule.myentity_info",
 *     "add-form" = "mymodule.myentity_add",
 *     "edit-form" = "mymodule.myentity_edit",
 *     "delete-form" = "mymodule.myentity_delete",
 *   }
 * )
 */

The MyEntityDeleteForm:

/**
 * @file
 * Contains \Drupal\mymodule\Form\MyEntityDeleteForm.
 */

namespace Drupal\mymodule\Form;

use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Url;

/**
 * Defines a confirmation form for deletion of a custom menu.
 */
class MyEntityDeleteForm extends EntityConfirmFormBase {

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return t('Are you sure you want to delete the myentity %title?', array('%title' => $this->entity->label()));
  }

  /**
   * {@inheritdoc}
   */
  public function submit(array $form, array &$form_state) {
    $this->entity->delete();
    drupal_set_message($this->t('The entity %title has been deleted.', array('%label' => $this->entity->label())));
    $form_state['redirect_route'] = $this->getCancelRoute();
  }

  public function getConfirmText() {
    return $this->t('Delete');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelRoute() {
    return $this->entity->urlInfo('canonical');
  }
}

The route defined in routing.yml:

mymodule.myentity_delete:
  path: '/admin/config/search/mymodule/myentity/{myentity}/delete'
  defaults:
    _entity_form: 'mymodule_myentity.delete'
  requirements:
    _entity_access: 'mymodule_myentity'

I'm getting this error while trying to delete the entity:

Notice: Undefined offset: 1 in Drupal\Core\Entity\EntityAccessCheck->access() (line 46 of core/lib/Drupal/Core/Entity/EntityAccessCheck.php).
Drupal\Core\Entity\EntityAccessCheck->access(Object, Object, Object)
call_user_func_array(Array, Array)
Drupal\Core\Access\AccessManager->performCheck('access_check.entity', Object, Object, Object)
Drupal\Core\Access\AccessManager->checkAll(Array, Object, Object, Object)
Drupal\Core\Access\AccessManager->check(Object, Object, Object)
Drupal\Core\EventSubscriber\AccessSubscriber->onKernelRequestAccessCheck(Object, 'kernel.request', Object)
call_user_func(Array, Object, 'kernel.request', Object)
Symfony\Component\EventDispatcher\EventDispatcher->doDispatch(Array, 'kernel.request', Object)
Symfony\Component\EventDispatcher\EventDispatcher->dispatch('kernel.request', Object)
Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.request', Object)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\HttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)

And this message on the page:

Access denied
You are not authorized to access this page.

If you look at EntityAccessCheck::access() you'll see this:

$requirement = $route->getRequirement('_entity_access');
list($entity_type, $operation) = explode('.', $requirement);

The second line is causing the notice, and your access check to subsequently fail. Basically, the access method is expecting (requiring, in fact) your permission to contain an entity type and access operation, separated by a ..

If you take the node module's routing file as an example:

node.delete_confirm:
  path: '/node/{node}/delete'
  defaults:
    _entity_form: 'node.delete'
    _title: 'Delete'
  requirements:
    _entity_access: 'node.delete'
  options:
    _node_operation_route: TRUE

I would suggest you just need to change your route to match:

mymodule.myentity_delete:
  path: '/admin/config/search/mymodule/myentity/{myentity}/delete'
  defaults:
    _entity_form: 'mymodule_myentity.delete'
  requirements:
    _entity_access: 'mymodule_myentity.delete'


How to show a block on pages with url parameters? I have a block that I want to show on pages matching news and news?page=1. In the 'only show on these pages' section I have news and news/* but it doesn't match the second url. Is there a way to do this?

Update 1: I have also tried this:

<?php
    $url = request_uri();
    if (strpos($url, "news")) {
    return TRUE;
        }
    ?>

But even after clearing all the caches it doesn't seem to have worked either.

I also tried the pattern news?page=* but that doesn't work either! Surely somebody considered being able to show blocks on paginated pages?

Update 2: Found the answer Restrict block to specific pages is broken when using view pagination

Turns out the block I was trying to display was a View which was also set to display a pager (even though one doesn't appear). Turning the pager off resolved the issue.


Obtaining all values from a built form I'm building a form and setting values via

$form = \Drupal::formBuilder()->getForm('My\Module', ['key1' => 'x']);

where I set the passed key1 as the default values for the associated fields : in My\Module\buildForm, you would find

public function buildForm(array $form, FormStateInterface $form_state, $presets = array()) {

    $form['key1'] = [
      '#type' => 'textfield',
      '#default_value' => isset($presets['key1']) ? $presets['key1'] : $query->get('key1')
    ];

    return $form;
}

This takes place in a controller not directly related to the form and I'd like to retrieve all values set, either as defaults or as parameters of the page, something like ['key1' => 'x'] if no parameter is passed to the page or ['key1' => 'v1'] if the page is called with ?key1=v1

How can I get all the values on my form array (besides filtering on the field names)?

Probably you put the preset values in the default values of form elements. They are at this point only in $form.

The values in $form_state are filled after the form is submitted, as a result of a GET/POST request.

But then your code, that calls the formBuilder, has no longer control. This will be handled by the submit method you have defined for the form.


how to add .install file to the new feature folder? I have created new feature and needs to add .install file to create new table like create new module way

but the table have not been created

can you advice me with the right way to do or i have to create a new module along with the feature
thanks in advance

If you stay out of the files that Features generated, you can add code to the (Features generated) module the way you normally do things.

The problem is that your module is already installed when you're adding the schema via .install. You'll need to implement hook_update_N and add the tables using db_create_table. Run update.php or drush updatedb and your schema should be created.


How to get taxonomy image and path by tid in Drupal 7? I want to get categiries image and path in Catalog Block for Ubercart 3 (Drupal 7) which is taxonomies. I know only tid.

For path i try this

$tid = (int)$variables['catid']; // return tid
$term = taxonomy_term_load($tid);
print_r(entity_uri('node', $term));

but site crashed.

I'm guessing you're looking for something like:

$term = taxonomy_term_load($tid);
if ($image_items = field_get_items('taxonomy_term', $term, 'field_name')) {
  $uri = $image_items[0]['uri'];
  $external_url = file_create_url($uri);
}

Where field_name is replaced with the name of your image field.


Drupal 7 view's operator "Is one of" In Drupal 5 there was a possibility to filter our content type's NIDs using "is one of" operator. So I have a view where I only used one filter like

Node: Node ID -> Is One Of -> <?php return callback_function() ?>

This callback_function() returns an array of NIDs and my view works just perfect. While moving project to Drupal 7 I discovered that there is no more such operator. Does anybody knows any possibility to use this good old "Is One Of" operator? Thank you!

Solution was to use View PHP module and Global: PHP field in filters.