We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 38666
    • 98 Posts
    As an update to earlier posts (https://forums.modx.com/thread/?thread=95538&page=1) I'm slowly getting my user CRUD together but would appreciate some guidance with a more efficient way of performing the following:

    Update
    <?php  
    $csaacID= $scriptProperties['ID']; 
    
    $csaacmember = $modx->getCollection('modUserProfile',array('internalKey'=>$csaacID));
      
    foreach($csaacmember as $Pmembers) {
        /* get user ID from profile object */
        $userId = $Pmembers->get('internalKey');
     
        /* get extended fields */
        $data = $modx->getObject('userData', array('userdata_id' => $userId));
     
        $fields = array_merge ($Pmembers->toArray(), $data->toArray() );
     
        /* Set $fields['id'] to true user ID */
        $fields['id'] = $userId;
    }
    
    // ////////////////////////////////////////////////  
    /* Show error message if quote is not found */
    if (empty($userId)) {
        return ('Could not find User with ID: ' . $userId);
    }
    // ///////////////////////////////////////////////
    // if (isset($_POST['MM_insert']) && $_POST['MM_insert'] == 'UpdateUser') {
    if (isset($_POST['submit']) && ($_POST['submit'] == 'MySubmitVar')) {
    	$z = " ";
    	$id = $_POST['ID'];
    	$name = $_POST['MemberName'];
    	$surname = $_POST['Surname'];
    	$newExtUser = $name.$z.$surname;
    	$newusename = $surname.substr($name, 0, 1);
    	$status = $_POST['Status'];
    	$seal = $_POST['Seal'];	
    	$company =$_POST['Company'];
    	$address = $_POST['Address'];
    	$city =$_POST['City'];
    	$state = $_POST['Prov'];
    	$postcode = $_POST['PostCode'];	
    	$country = $_POST['Country'];
    	$phone = $_POST['Phone'];
    	$fax = $_POST['Fax'];
    	$email = $_POST['Email'];
    	$role = 5;
    	//
    	$blockedafter= strtotime($_POST['blockedafter']);	// strtotime("1 February 2016")
    	$newusename = $fields[1].substr($fields[2], 0, 1);
    	
    	// Generate Password 
    		$length = 10;
    		$allowable_characters = "abcdefghjkmnpqrstuvxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    		$ps_len = strlen($allowable_characters);
    		mt_srand((double)microtime()*1000000);
    		$pass = "";
    		for($i = 0; $i < $length; $i++) {
    			$pass .= $allowable_characters[mt_rand(0,$ps_len-1)];
    		}
    	$pwd = $pass;
    	$comment = $pwd;
    	
    	$user = $modx->getObject('modUser', array('id' => $userId));
    	$user->set('username', $newExtUser);
    	$user->set('password', $pwd);
    	//$user->set('active', '0');
    	$user->set('blocked', '1');
    	$user->set('primary_group',$role); 
    	$user->save();
    	
    	// Create the userData Object 
    	$data = $modx->getObject('userData', array('userdata_id' => $userId));
    	$data->set('firstName', $name);
    	$data->set('lastName', $surname);       
    	$data->set('status', $status);
    	$data->set('seal', $seal);
    	$data->set('company', $company);
    	$data->save();  
       
    	// Create the User Profile //
    	$profile = $modx->getObject('modUserProfile', array('internalKey' => $userId));
    	$profile->Set('fullname', $newExtUser );
    	$profile->Set('blocked', '1');
    	$profile->Set('blockedafter', $blockedafter);
    	$profile->set('email', $email);
    	$profile->set('phone', $phone);
    	$profile->set('address', $address);
    	$profile->set('country', $country);
    	$profile->set('city', $city);
    	$profile->set('state', $state);
    	$profile->set('zip', $postcode);
    	$profile->set('fax',$fax);
    	$profile->set('comment',$pwd);
    	$profile->set('website', $web);
    	$profile->save(); 
    
     if ( $user->save()) {
    	$uid = $user->get('id');
    	$output .= "" . '<div><br/><em><strong><div><br/><em><strong>Updated user: ' . $newExtUser." ".$uid."<br></br>";
    	} else {
    	$output .= "" . '<div><br/><em><strong>Error updating user: ' . $newExtUser."<br></br>";
    	}
    	$output .= ""."<a title='Show Members' href='[[~104]]'><img style='vertical-align: middle; margin-left: 10px; margin-right: 10px;' title='Return' src='assets/images/icons/rewnd_24.gif' alt='Return' width='24' height='24' />Return to Member List  </a></br></br>".""."<a href='[[~68]]&ID=".$uid."'><img src='assets/images/icons/addbk_24.gif'/>Review this Member</a> </div>";
    
    } else {
    /* Not a repost, just display the form */
    $output .= $modx->getChunk('UpdateUser', $fields);
    }
    return $output;
    


    Delete
    <?php
    $csaacID= $scriptProperties['ID']; 
    
    /* delete user profile */
    $del_userProfile = $modx->removeCollection('modUserProfile',array('internalKey'=>$csaacID));  
    /* delete user */
    $removed = $modx->removeCollection('modUser', array('id' => $csaacID ));
     #del_user->remove()
    /* delete extended data*/
        $data = $modx->getObject('userData', array('userdata_id' => $csaacID ));  
    
    if ($data->remove() == false) {
    echo 'The Member failed to remove.';
    }
    else
    {echo "Member Removed. <a title='Show Members' href='[[~104]]'><img style='vertical-align: middle; margin-left: 10px; margin-right: 10px;' title='Return' src='assets/images/icons/rewnd_24.gif' alt='Return' width='24' height='24' />Return to Member List  </a>";}
    


    Not at all pretty, but both finally function. Any suggestions to improve the operations of the snippets would most appreciated
      Give a man the answer, and he’ll only have a temporary solution. Teach him the principles that led you to that answer, and he will be able to create his own solutions in the future.
      • 40706
      • 128 Posts
      You can generate Password just with the modUser Object using $user->generatePassword().

      $csaacmember should never return more then one Object, because of querying by it. So it could just an getObject without foreach.

      catch errors, when $modx->getObject() fails in any call of your, snippet, an php_error would be resulted, because of just using methods like ->toArray() on the result. You should always check if the results are ok, Even if its just an return Error or redirect to some error page
      if(!$data) $modx->sendErrorPage();


      Removing the userProfile is unnecessary, as it is an composite of moduser. Just delete the user and if that succeed, the Profile is also gone.
        • 38666
        • 98 Posts
        Thanks Michael, Good points, I'll implement your suggestions.
          Give a man the answer, and he’ll only have a temporary solution. Teach him the principles that led you to that answer, and he will be able to create his own solutions in the future.
          • 49529
          • 196 Posts
          jimsheppard,
          according to http://rtfm.modx.com/revolution/2.x/developing-in-modx/basic-development/snippets/how-to-write-a-good-snippet, direct HTML output like this
          $output .= "" . '<div><br/><em><strong><div><br/><em><strong>Updated user: ' . $newExtUser." ".$uid."<br></br>";

          is considered to be a bad practice, snippet output should instead be templated via $modx->getChunk().