2

I created a custom module that can save nodes.

I want a checkbox that determines whether the node will be saved or not.

This is the node_save program :

     global $user;

// IF (FORM_STATE [VALUE][CHECKBOX] == Checked ! ) {


        $node = new stdClass();
        $node->type = "services";
        node_object_prepare($node);
        $node->language = 'fr'; // Or e.g. 'en' if locale is enabled
        $node->uid = $user->uid;
        $node->status = 1; //(1 or 0): published or not
        $node->promote = 0; //(1 or 0): promoted to front page
        $node->comment = 1; // 0 = comments disabled, 1 = read only, 2 = read/write
        $node->title = $form_state['values']['produit_de_client'];

        $node->field_produit_dc['und'][0]['value'] = $produit;
          $node->field_espace_dediee_categories[LANGUAGE_NONE][0]['tid']=$form_state['values']['espace_dediee'];


        $node->body['und'][0]['value'] =$form_state['values']['text_service'];
        $node->body['und'][0]['format'] ='full_html';

        $aaz= array_filter($form_state['values']['wrapperrr']['id_offre']);
     foreach($aaz as $of)
       {       

       $node->field_offre[LANGUAGE_NONE][]['target_id'] = $of;



       } 

        $node->field_id_prod['und'][0]['value'] = $produit;
            $file = file_load($form_state['values']['image_dc']);
            $file->status = FILE_STATUS_PERMANENT;

            $uploaded = file_save($file);
            $aaa = file_create_url($file->uri);
        $node->field_produit_dc['und'][0]['value'] = $file->fid;
        $url = $file->uri;

        $node->field_image_serv[LANGUAGE_NONE][0]['fid'] = $file->fid;

        node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().



        $node = node_submit($node); // Prepare node for saving
        node_save($node);

//ELSE NO NODE WILL BE SAVED
0

1 Answer 1

1

In a nutshell:

function mymodule_form_submit($form, &$form_state) {
  if ($form_state['values']['mycheckbox'] == 1) {
    // node code...
    node_save($node);
    drupal_set_message('Node saved.');
    $form_state['redirect'] = 'some/path';
  }
}

Or you could just require the checkbox in the form:

$form['mycheckbox'] = [
  // props
  '#required' => TRUE,
];

If the checkbox is required, the form can't be submitted, and thus the node won't be created.

I would probably require the field(s) instead of silently do nothing on submit if they did not check it. That way the form submit won't get hit and the user won't have to re-enter all of the information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.