简体   繁体   中英

Drupal - allow only 1 node of a content type to be 'featured'

I have a Drupal 7 site with several custom content types. For one, "banners", there is a field (check box) to flag the banner as being featured. (gives it more prominence where displayed).

How can I restrict the content type of "banners' to only allow 1 published item to be featured at any time?

Are you using the flags module for the flagging?

Whether you are or not, you're going to want to write some custom code, be it using the Flags API to work out whether there is already a flag, or using some custom SQL or entity query to pull the flags for everything, and if there is one already then to act accordingly.

You can't do that. But check out the part that is displaying those banners - probably it's a view so set it's limit to 1.

Custom code will be needed as far as I am aware.

In the example below, I am checking a property named 'featured_article', which can be added quite easily using the Custom Publishing Options module.

It will need a little modification if your 'featured' field is just a standard checkbox field which you added to the node, but the logic remains the same.

First, in a hook_node_submit, check if the 'featured_article' property in question is enabled (add this to a custom module or your template.php):

function <THEME_OR_MODULE_NAME>_node_submit($node, $form, &$form_state)
{
    // If featured is set, set all other nodes to not featured
    if ($form_state['node']->featured_article == 1 && $form_state['node']->type == 'banners') {
        <THEME_OR_MODULE_NAME>_set_as_only_featured_node($form_state['node']->nid);
    }
}

Then add the function you are calling above that checks for any others enabled, and disable them as necessary:

function <THEME_OR_MODULE_NAME>_set_as_only_featured_node($nid)
{
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'banners')
        ->propertyCondition('nid', $nid, '!=')
        ->propertyCondition('featured_article', 1);

    $results = $query->execute();

    if (!empty($results['node'])) {
        foreach ($results as $result) {
            $node = node_load(key($result));
            $node->featured_article = 0;
            node_save($node);
        }
    }
}

A very easy way to do this is by setting up Nodequeue and setting the queue to only allow one item of that content type. The Nodequeue UI is easy to use and, if this is for a client, they have the ability to switch it out very easily without tinkering with code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM