eate Create a new method in the Calendar class - PHP and Jquery

To save events entered in the form, you create a new method in the Calendar class called processForm() that accomplishes the following:

  • Sanitizes the data passed from the form via POST
  • Determines whether an event is being edited or created
  • Generates an INSERT statement if no event is being edited; or it generates an UPDATE statement if an event ID was posted
  • Creates a prepared statement and binds the parameters
  • Executes the query and returns TRUE or the error message on failure

The following code creates the processForm() method in the Calendar class:

<?php

class Calendar extends DB_Connect

{

private $_useDate;

private $_m;

private $_y;

private $_daysInMonth;

private $_startDay;

public function __construct($dbo=NULL, $useDate=NULL) {...}

public function buildCalendar() {...}

public function displayEvent($id) {...}

public function displayForm() {...}

/**

* Validates the form and saves/edits the event

*

* @return mixed TRUE on success, an error message on failure

*/

public function processForm()

{

/*

* Exit if the action isn't set properly

*/

if ( $_POST['action']!='event_edit' )

{

return "The method processForm was accessed incorrectly";

}

/*

* Escape data from the form

*/

$title = htmlentities($_POST['event_title'], ENT_QUOTES);

$desc = htmlentities($_POST['event_description'], ENT_QUOTES);

$start = htmlentities($_POST['event_start'], ENT_QUOTES);

$end = htmlentities($_POST['event_end'], ENT_QUOTES);

/*

* If no event ID passed, create a new event

*/

if ( empty($_POST['event_id']) )

{

$sql = "INSERT INTO `events`

(`event_title`, `event_desc`, `event_start`,

`event_end`)

VALUES

(:title, :description, :start, :end)";

}

/*

* Update the event if it's being edited

*/

else

{

/*

* Cast the event ID as an integer for security

*/

$id = (int) $_POST['event_id'];

$sql = "UPDATE `events`

SET

`event_title`=:title,

`event_desc`=:description,

`event_start`=:start,

`event_end`=:end

WHERE `event_id`=$id";

}

/*

* Execute the create or edit query after binding the data

*/

try

{

$stmt = $this->db->prepare($sql);

$stmt->bindParam(":title", $title, PDO::PARAM_STR);

$stmt->bindParam(":description", $desc, PDO::PARAM_STR);

$stmt->bindParam(":start", $start, PDO::PARAM_STR);

$stmt->bindParam(":end", $end, PDO::PARAM_STR);

$stmt->execute();

$stmt->closeCursor();

return TRUE;

}

catch ( Exception $e )

{

return $e->getMessage();

}

}

private function _loadEventData($id=NULL) {...}

private function _createEventObj() {...}

private function _loadEventById($id) {...}

}

?>

Adding a Processing File to Call the Processing Method

The form to add and edit events is submitted to a file called process .inc .php, which is located in the inc folder (/public /assets /inc /process .inc .php). This file checks the submitted form data and saves or updates entries by performing the following steps:

1. Enables the session.

2. Includes the database credentials and the Calendar class.

3. Defines constants (as occurs in the initialization file).

4. Creates an array that stores information about each action.

5. Verifies that the token was submitted and is correct, and that the submitted action exists in the lookup array. If so, go to Step 6. If not, go to Step.

6. Creates a new instance of the Calendar class.

7. Calls the processForm() method.

8. Sends the user back to the main view or output an error on failure.

9. Sends the user back out to the main view with no action if the token doesn’t match.

The array created in Step 4 allows you to avoid a long, repetitive string of if...elseif blocks to test for each individual action. Using the action as the array key and storing the object, method name, and page to which the user should be redirected as array values means that you can write a single block of logic using the variables from the array.

Insert the following code into process.inc.php to complete the steps just described:

<?php

/*

* Enable sessions

*/

session_start();

/*

* Include necessary files

*/

include_once '../../../sys/config/db-cred.inc.php';

/*

* Define constants for config info

*/

foreach ( $C as $name => $val )

{

define($name, $val);

}

/*

* Create a lookup array for form actions

*/

$actions = array(

'event_edit' => array(

'object' => 'Calendar',

'method' => 'processForm',

'header' => 'Location: ../../'

)

);

/*

* Make sure the anti-CSRF token was passed and that the

* requested action exists in the lookup array

*/

if ( $_POST['token']==$_SESSION['token']

&& isset($actions[$_POST['action']]) )

{

$use_array = $actions[$_POST['action']];

$obj = new $use_array['object']($dbo);

if ( TRUE === $msg=$obj->$use_array['method']() )

{

header($use_array['header']);

exit;

}

else

{

// If an error occured, output it and end execution

die ( $msg );

}

}

else

{

// Redirect to the main index if the token/action is invalid

header("Location: ../../");

exit;

}

function __autoload($class_name)

{

$filename = '../../../sys/class/class.'

. strtolower($class_name) . '.inc.php';

if ( file_exists($filename) )

{

include_once $filename;

}

}

?>

Save this file, and then navigate to http://localhost/admin.php and create a new event with the following information:

Event Title: Dinner Party

Start Time: 2010-01-22 17:00:00

End Time: 2010-01-22 19:00:00

Description: Five-course meal with wine pairings at John’s house

After clicking the Create new event button, the calendar is updated with the new event.

The new event as it appears when hovered over

Submit

Adding a Button to the Main View to Create New Events

To make it easier for your authorized users to create new events, add a button to the calendar that takes the user to the form in admin.php. Do this by creating a new private method called _adminGeneralOptions() in the Calendar class:

<?php

class Calendar extends DB_Connect

{

private $_useDate;

private $_m;

private $_y;

private $_daysInMonth;

private $_startDay;

public function __construct($dbo=NULL, $useDate=NULL) {...}

public function buildCalendar() {...}

public function displayEvent($id) {...}

public function displayForm() {...}

public function processForm() {...}

private function _loadEventData($id=NULL) {...}

private function _createEventObj() {...}

private function _loadEventById($id) {...}

/**

* Generates markup to display administrative links

*

* @return string markup to display the administrative links

*/

private function _adminGeneralOptions()

{

/*

* Display admin controls

*/

return <<<ADMIN_OPTIONS

<a href="admin.php" class="admin">+ Add a New Event</a>

ADMIN_OPTIONS;

}

}

?>

Note Checks to ensure that this button is only displayed to authorized users.

Next, modify the build Calendar() method to call your new _admin General Options() method by inserting the following bold code:

public function buildCalendar()

{

// To save space, the bulk of this method has been omitted

/*

* Close the final unordered list

*/

$html .= "\n\t</ul>\n\n";

/*

* If logged in, display the admin options

*/

$admin = $this->_adminGeneralOptions();

/*

* Return the markup for output

*/

return $html . $admin;

}

Finally, add the admin stylesheet (admin.css) to index.php using the following code in bold to make sure the link displays correctly:

<?php

/*

* Include necessary files

*/

include_once '../sys/core/init.inc.php';

/*

* Load the calendar

*/

$cal = new Calendar($dbo, "2010-01-01 12:00:00");

/*

* Set up the page title and CSS files

*/

$page_title = "Events Calendar";

$css_files = array('style.css', 'admin.css');

/*

* Include the header

*/

include_once 'assets/common/header.inc.php';

?>

<div id="content">

<?php

/*

* Display the calendar HTML

*/

echo $cal->buildCalendar();

?>

</div><!-- end #content -->

<?php

/*

* Include the footer

*/

include_once 'assets/common/footer.inc.php';

?>

Save the file and reload http://localhost/ to see the button.

The Admin button appears in the bottom left of the calendar

Submit


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP and Jquery Topics