Вывести сообщение при нажатии на кноку сразу

Discussion in 'PHP' started by rushelp, 18 Sep 2012.

Thread Status:
Not open for further replies.
  1. rushelp

    rushelp New Member

    Joined:
    13 Sep 2011
    Messages:
    2
    Likes Received:
    0
    Reputations:
    0
    Здравствуйте,

    Я пытаюсь переделать этот код. К сожелению я не очень то силен в пхп.

    Code:
    <?php
    
    //include custom library
    require_local_theme_path('maydit/models/MayditBook.php');
    require_local_theme_path('maydit/models/MayditBookPage.php');
    
    $currentUser = wp_get_current_user();
    $updateBook = FALSE;
    if (count($_GET)) {
    	$book = R::load('maydit_book', $_GET['book']);
    	$getValidator = new Validator($_GET);
    	$getValidator
    		->callback(function($bookID) use ($book, $currentUser) {
    			return $book->belongsToUser($currentUser->ID);
    		}, 'You do not have permission to edit this book.')
    		->validate('book');
    	if ($getValidator->hasErrors()) {
    		$_POST['errors'] = $getValidator->getAllErrors();
    	}
    	else {
    		if (!count($_POST)) {
    			$_POST['title'] = $book->title;
    			$_POST['abstract'] = $book->abstract;
    			$_POST['writtenby'] = $book->writtenby;
    		}
    		$updateBook = TRUE;
    	}
    }
    if ($_POST['submit']) {
    	$createUser = !is_user_logged_in();
    	try {
    		if (!wp_verify_nonce($_POST['book_creation_nonce'], 'create_book')) {
    			throw new Exception("Error: The security nonce could not be verified.");
    		}
    		$validator = new Validator($_POST);
    		$validator
    			->filter('trim_and_remove_special')
    			->filter('no_magic_quotes')
    			->required("You need to enter a book title.")
    			->validate('title');
    		$validator
    			->filter('trim_and_remove_special')
    			->filter('no_magic_quotes')
    			->required("You need to enter a book abstract.")
    			->validate('abstract');
    		$validator
    			->filter('trim_and_remove_special')
    			->filter('no_magic_quotes')
    			->required("You need to enter a pen name.")
    			->validate('writtenby');
    		if ($createUser) {
    			$validator
    				->filter(function($val) {
    					$val = trim_and_remove_special($val);
    					$val = sanitize_email($val);
    					return $val;
    				})
    				->required("You need to enter a valid e-mail address.")
    				->callback(function($val) {
    					return is_email($val);
    				}, "You need to enter a valid e-mail address.")
    				->callback(function($val) {
    					return !email_exists($val);
    				}, 'The e-mail address you entered is already in use.')
    				->validate('email');
    			$validator
    				->filter(function($val) {
    					$val = trim_and_remove_special($val);
    					$val = sanitize_user($val);
    					return $val;
    				})
    				->minLength(4, 'You need to enter a valid username at least four characters long.')
    				->callback(function($val) {
    					return !username_exists($val);
    				}, 'The username you entered already exists.')
    				->validate('username');
    			$validator
    				->minLength(6, "Your password must be at least six characters long.")
    				->validate('pass');
    		}
    		
    		if ($validator->hasErrors()) {
    			// Puts data back into form if errors exist
    			$data = $validator->getData();
    			$title = $_POST['title'] = $data['title'];
    			$abstract = $_POST['abstract'] = $data['abstract'];
    			$writtenby = $_POST['writtenby'] = $data['writtenby'];
    			if ($createUser) {
    				$email = $_POST['email'] = $data['email'];
    				$username = $_POST['username'] = $data['username'];
    				$pass = $_POST['pass'] = $data['pass'];
    			}
    			throw new Validator_Exception('Validation encountered errors.', $validator->getAllErrors());
    		}
    		
    		$validData = $validator->getValidData();
    		$title = $_POST['title'] = $validData['title'];
    		$abstract = $_POST['abstract'] = $validData['abstract'];
    		$writtenby = $_POST['writtenby'] = $validData['writtenby'];
    		
    		// Creates a new user from the validated data
    		$user_id = null;
    		if ($createUser) {
    			$email = $_POST['email'] = $validData['email'];
    			$username = $_POST['username'] = $validData['username'];
    			$pass = $_POST['pass'] = $validData['pass'];
    			
    			//$user_id = wp_create_user( $username, $pass, $email );
    			$user_id = wp_insert_user(array(
    				'user_login' => $username,
    				'display_name' => sanitize_title( $username ),
    				'user_pass' => $pass,
    				'user_email' => $email
    			));
    			if (is_wp_error($user_id)) {
    				throw new Exception('Registration error: ' . $user_id->get_error_message());
    			}
    			else {
    				// Signs on new user if they were able to create an account
    				$user = wp_signon(array('user_login' => $username, 'user_password' => $pass), true);
    				if (is_wp_error($user)) {
    					throw new Exception('Login error: ' . $user->get_error_message());
    				}
    				do_action('bp_core_new_user_activity', $user_id);
    			}
    		}
    		$currentUser = wp_get_current_user();
    		
    		// Creates a new book
    		$userID = ($createUser) ? $user_id : $currentUser->ID;
    		if ($updateBook) {
    			$book->title = $title;
    			$book->abstract = $abstract;
    			$book->writtenby = $writtenby;
    		}
    		 else {
    		 	$book = Model_maydit_book::createBook($userID, $title, $abstract, $writtenby);
    		 }
    		$bookID = R::store($book);
    		$book = R::load('maydit_book', $bookID);
    		if (!$bookID) {
    			throw new Exception("Unable to save book.");
    		}
    		header('Location: ../author-content-2-1/?book=' . $bookID);
    	}
    	catch(Validator_Exception $e) {
    		$_POST['errors'] = $e->getErrors();
    	}
    	catch(Exception $e) {
    		$_POST['errors'] = array($e->getMessage());
    	}
    }
    
    
    function maydit_set_activation_send() {
    	return false;
    }
    ?>
    
    <?php 
    //$test = new redbeantest();
    //$test->test_redbean();
    
    ?>
    
    <?php 
    class redbeantest
    {
    	public function test_redbean(){
    		
    		//load a book by its id
    		$book = R::load('maydit_book',3);
    		echo "the loaded book is: $book->title $book->abstract $book->writtenby $book->pdf $book->flipbookid";	
    		
    		//loading a book by its user id
    		$book = R::find('maydit_book','user = ?', array("1"));
    		echo "<br>the loaded book for user 1 is: $book->title $book->abstract $book->writtenby $book->pdf $book->flipbookid";
    		
    		//creating a book
    		$book = Model_maydit_book::createBook("9999", "testTitle", "testAbstract", "testWrittentBy","testPdf", "testFlipbookId");
    		
    		//storing a book
    		$bookID = R::store($book);
    		echo "<br> i just stored the book and got back bookID: $bookID";
    		echo "<br>this book is: $book->title $book->abstract $book->writtenby $book->pdf $book->flipbookid";
    		
    		//changing a book attribute
    		$book->flipbookid = "newFlipbookId";
    		echo "<br>this book with changed flipbookid is: $book->title $book->abstract $book->writtenby $book->pdf $book->flipbookid";
    		$bookID = R::store($book);
    		
    		//deleting the book
    		R::trash($book);
    	}
    }
    ?>
    
    и

    Code:
    <?php
    if (!is_user_logged_in()) {
    ?>
    <script type="text/javascript" id ="popup">
      $(document).ready(function() {
        $("#lightboxRegister").colorbox({inline:true, width:"50%"});
        $("#lightboxRegister").click(function() {
          $("#title").attr("value", $("#title-vis").val());
          $("#abstract").attr("value", $("#abstract-vis").val());
          $("#writtenby").attr("value", $("#writtenby-vis").val());
        });
      });
    </script>
    <?php
    }
    
    $permalink = self_url();
    if (is_user_logged_in()) {
    	echo '<form action="' . $permalink . '" method="post">';
    }
    echo '<div style="margin-top: 150px; margin-left: 30px;">';
    echo '<h1>Take your manuscript out of the drawer and upload it to maydit. Start now!</h1>';
    
    //START RATING-WIDGET
    /* echo '
    <div class="movie_choice">
    	Rate: Adventures of CuddleBug
    	<div id="r1" class="rate_widget">
    	<div class="star_1 ratings_stars"></div>
    	<div class="star_2 ratings_stars"></div>
    	<div class="star_3 ratings_stars"></div>
    	<div class="star_4 ratings_stars"></div>
    	<div class="star_5 ratings_stars"></div>
    	<div class="total_votes">vote data</div>
    	</div>
    </div>'; */
    //END RATING WIDGET
    
    echo '<h2>All fields are required.</h2>';
    $errorMsgs = $_POST['errors'];
    if ($errorMsgs) {
    	foreach ($errorMsgs as $key => $message) {
      		echo do_shortcode('[message_box type="error" icon="yes"]' . $message . '[/message_box]') . '<br />';
    	}
    }
    
    if (is_user_logged_in()) {
    	$titleID = "title";
    	$titleName = 'name="title"';
    	
    	$abstractID = "abstract";
    	$abstractName = 'name="abstract"';
    	
    	$writtenbyID = 'writtenby';
    	$writtenbyName = 'name="writtenby"';
    }
    else {
    	$titleID =  "title-vis";
    	$titleName = '';
    	
    	$abstractID = "abstract-vis";
    	$abstractName = '';
    	
    	$writtenbyID = 'writtenby-vis';
    	$writtenbyName = '';
    }
    
    echo do_shortcode('[one_fifth]<label for="' . $titleID . '"><span style="font-size: 20px; vertical-align: middle;">1. Title</span></label>[/one_fifth]') . 
    		do_shortcode('[four_fifth_last]<input id="' . $titleID . '" ' . $titleName . ' type="text" maxlength="100" size="125" value="' . $_POST['title'] . '" placeholder="Enter the working title of your book. You can change the title and other items below later."/>[/four_fifth_last]') .
    		do_shortcode('[clear]') . '<br /><br />';
    
    echo do_shortcode('[one_fifth]<label for="' . $abstractID . '"><span style="font-size: 20px; vertical-align: middle;">2. Abstract</span></label>[/one_fifth]') . 
    		do_shortcode('[four_fifth_last]<input id="' . $abstractID . '" ' . $abstractName . ' type="text" maxlength="100" size="125" value="' . $_POST['abstract'] . '" placeholder="Describe your book in 10 words or fewer. For example: three pigs build houses, wolf intrudes, one piggy outsmarts him." />[/four_fifth_last]') .
    		do_shortcode('[clear]') . '<br /><br />';
    
    echo do_shortcode('[one_fifth]<label for="' . $writtenbyID . '"><span style="font-size: 20px; vertical-align: middle;">3. Written by</span></label>[/one_fifth]') . 
    		do_shortcode('[four_fifth_last]<input id="' . $writtenbyID . '" ' . $writtenbyName . ' type="text" maxlength="100" size="125" value="' . $_POST['writtenby'] . '" placeholder="Enter your name or pen name as you\'d like it to appear on your book\'s cover and on your maydit profile."/>[/four_fifth_last]') .
    		do_shortcode('[clear]') . '<br /><br />';
    
    echo do_shortcode('[clear]') . '<br /><br />';
    
    $submit_button_type = (!is_user_logged_in()) ? 'type="button" href="#save-and-continue" id="lightboxRegister"' : 'type="submit" name="submit"';
    echo '<div style="width: 17.1%; float: left; margin-right: 3%;">&nbsp;</div><input class="btn large orange" ' . $submit_button_type . ' value=" Save and continue adding content... " />';
    echo do_shortcode('[clear]');
    if (is_user_logged_in()) {
    	wp_nonce_field('create_book', 'book_creation_nonce');
    	echo "</form>";
    }
    echo '<br /><div style="width: 17.1%; float: left; margin-right: 3%;">&nbsp;</div><form action="../community/"  method="post"><input type="submit" class="btn small white" value="...Or skip this and browse the mayker community." /></form>';
    echo do_shortcode('[clear]'); 
    
    if (!is_user_logged_in()) {
    	$permalink = self_url();
    	echo '<div style="display: none;">' . 
    	'<div id="save-and-continue" style="padding: 15px 15px;">' . 
    	'<form action="' . $permalink . '" method="post">' .  
    	'<h2>You\'ll need to register an account so we can save your progress. Don\'t worry; here\'s all you need to get started:</h2>' . 
    	do_shortcode('[two_fifth]<label for="email"><span style="font-size: 18px; vertical-align: middle;">E-mail</span></label>[/two_fifth]') . 
    	do_shortcode('[three_fifth_last]<input id="email" name="email" type="text" maxlength="100" size="50" value="' . $_POST['email'] . '" />[/three_fifth_last]') . 
    	do_shortcode('[clear]') . 
    	'<br />' . 
    	do_shortcode('[two_fifth]<label for="username"><span style="font-size: 18px; vertical-align: middle;">Username</span></label>[/two_fifth]') . 
    	do_shortcode('[three_fifth_last]<input id="username" name ="username" type="text" maxlength="60" size="50" value="' . $_POST['username'] . '" />[/three_fifth_last]') . 
    	do_shortcode('[clear]') . 
    	'<br />' . 
    	do_shortcode('[two_fifth]<label for="pass"><span style="font-size: 18px; vertical-align: middle;">Password</span></label>[/two_fifth]') . 
    	do_shortcode('[three_fifth_last]<input id="pass" name="pass" type="password" maxlength="100" size="50"/>[/three_fifth_last]') . 
    	do_shortcode('[clear]') . 
    	'<br /> 
    	<input id="title" name="title" type="hidden" maxlength="100" size="100"/> 
    	<input id="abstract" name="abstract" type="hidden" maxlength="100" size="100"/> 
    	<input id="writtenby" name="writtenby" type="hidden" maxlength="100" size="100"/>';
    	wp_nonce_field('create_book', 'book_creation_nonce');
    	echo '<div style="width: 37.8%; float: left; margin-right: 3%;">&nbsp;</div><input type="submit" class="btn large orange" value="Let\'s get this show on the road!" name="submit" id="registerSubmit"/>
    	</div>';
    	echo '</form></div></div>';
    }
    ?>
    
        <br /><br /><br />
        <center>
    	    <div align="center" class="you-are-here">
    	    	<br />
    	        <img src="../wp-content/images/maydit-images/1_medium.gif" alt="You are here: Step one" width="150" height="89"/>
    	        <img src="../wp-content/images/maydit-images/2_medium.gif" alt="You are here: Step two" width="100" height="89"/>
    	        <img src="../wp-content/images/maydit-images/3_medium.gif" alt="You are here: Step three" width="100" height="89"/>
        </div>
        </center>
    

    Данный код работает, только мне нужно ее переделать чуть чуть.

    На данной странице нужно заполнит 3 поля и потом уже нажат на кнопку, чтобы зарегистрироваться. После нажатии кнопки появляется маленькое окошко, чтобы заполнит имейл, пароль, и логин. И только когда нажимаешь на кнопку зарегистрироваться она показывает какие поля не заполнены, и сообщение о том чтоб заполнит эти поля.

    Я хотел чтобы пользователь не смог нажать на кнопку "Save and continue adding content..." пока не заполнил все 3 поля. Сообщение о том что нужно заполнит все необходимые поля выдавала сразу по нажатию кнопки а не после регистрации.

    Пожалуйста помогите.
    Спасибо.
     
  2. Gifts

    Gifts Green member

    Joined:
    25 Apr 2008
    Messages:
    2,494
    Likes Received:
    807
    Reputations:
    614
    http://php.net - там есть все что вам надо, я проверил.
     
    _________________________
Thread Status:
Not open for further replies.