I need to display the standard Add to Cart button for all logged in users, but anonymous users should instead see text and a link asking them to create an account or login in order to be able to add to cart. The code below works great, but it is applicable to individually-specific products only; I need it to apply to all products site-wide. How would I modify this code to accomplish this, given the fact that all Ubercart add to cart buttons contain the node ID and are thus all unique? the example shows the code applying to the product with node ID "3".

function uc_disable_cart_button_for_anonymous_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'uc_product_add_to_cart_form_3':
        // hide add to cart button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            drupal_set_message('Please <a href="/user/login">login</a> or <a href="/user/register">create a free Member account</a> in order to proceed.');
            $form['html_markup'] = array('#markup' => t('<div class="login-to-buy">Please <a href="/user/login">login</a> or <a href="/user/register">create a free Member account</a> in order to proceed.</div>'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '<div id="form-button-wrapper">';
            $form['actions']['submit']['#suffix'] = '</div>';
        }
        break;
    }
}

Thanks!

Comments

hockey2112 created an issue. See original summary.

TR’s picture

Status: Active » Fixed

Instead of the switch, use something like

if (strpos($form_id, 'add_to_cart_form')) {
  // Put your code in here.
}
hockey2112’s picture

That worked great, thank you! Here is my final code:

function uc_disable_cart_button_for_anonymous_form_alter(&$form, &$form_state, $form_id) {
    if (strpos($form_id, 'add_to_cart_form')) {
        // hide add to cart button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            $form['html_markup'] = array('#markup' => t('<div class="login-to-buy">Please login or apply for a Member account in order to proceed.<br><br><a href="/user/login" class="btn">Log In</a> &nbsp; <a href="/user/register" class="btn">Apply for Member account</a></div>'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '<div id="form-button-wrapper">';
            $form['actions']['submit']['#suffix'] = '</div>';
        }
    }
}

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.