FuelPHP framework jQuery DateTimePicker

I have recently started learning about the FuelPHP framework. I have been working on understanding how to use the framework as intended by the creators, and I think I’m doing a fair job of that, except possibly with regards to using external jQuery libraries.

I have a simple CRUD application that I built as a proof of concept for using a third party jQuery DateTimePicker library.

This is the jQuery DateTimePicker library that I found and used.

This is not including the public asset folder that contains the actual Javascript and CSS.

Model
fuel/app/classes/model/dtpsample.php

<?php
class Model_Dtpsample extends Model_Crud
{
	protected static $_table_name = 'dtpsample';
	
	public static function validate($factory)
	{
		$val = Validation::forge($factory);
		$val->add_field('name', 'Name', 'required|max_length[255]');
		$val->add_field('event_date', 'Event Date', 'required');
		

		return $val;
	}

}

View Template
fuel/app/views/template_dtpsample.php

I want to specifically point out this piece of code. The main thing to notice is Asset::js and the JavaScript code.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title><?php echo $title; ?></title>
	<?php echo Asset::css('bootstrap.css'); ?>
	<?php echo Asset::css('jquery.datetimepicker.css'); ?>
	
	
	<style>
		body { margin: 40px; }

	</style>
	
	<?php 
	     echo Asset::js(array(
		'//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js',
		'bootstrap.js',
		'jquery.datetimepicker.js',
		'moment.js',
		'moment-timezone.js'
	)); 
	?>
	
	
	
	<script type="text/javascript">
  $(function() {
      
    $("#form_name").focus();  

    $('#form_event_date').datetimepicker({
        formatTime:'g:i A', 
        //format:'Y-m-d h:i A',
        format:'unixtime',
        step:30,
        inline:true,
        onChangeDateTime:function(dp,$input){
    //$("#form_event_date").val($input.val());
    
    var strDate = moment.unix($input.val()).format("YYYY-MM-DD h:mm a");
    //var dtDate = new Date($input.val() * 1000).format('Y-m-d h:i:s a')
    $("#dtResult").val(strDate);

  }
    });
    
    
  

  });
  
  
  
</script>
</head>
<body>
	<div class="container">
		<div class="col-md-12">
			<h1><?php echo $title; ?></h1>
			<hr>
<?php if (Session::get_flash('success')): ?>
			<div class="alert alert-success">
				<strong>Success</strong>
				<p>
				<?php echo implode('</p><p>', e((array) Session::get_flash('success'))); ?>
				</p>
			</div>
<?php endif; ?>
<?php if (Session::get_flash('error')): ?>
			<div class="alert alert-danger">
				<strong>Error</strong>
				<p>
				<?php echo implode('</p><p>', e((array) Session::get_flash('error'))); ?>
				</p>
			</div>
<?php endif; ?>
		</div>
		<div class="col-md-12">
<?php echo $content; ?>
		</div>
		<footer>
			<p class="pull-right">Page rendered in {exec_time}s using {mem_usage}mb of memory.</p>
			<p>
				<a href="http://fuelphp.com">FuelPHP</a> is released under the MIT license.<br>
				<small>Version: <?php echo e(Fuel::VERSION); ?></small>
			</p>
		</footer>
	</div>
</body>
</html>

Screenshot of the DateTimeStamp picker on the page.

Views
fuel/app/views/dtpsample/_form.php

<?php echo Form::open(array("class"=>"form-horizontal")); ?>

	<fieldset>
		<div class="form-group">
			<?php echo Form::label('Name', 'name', array('class'=>'control-label')); ?>

				<?php echo Form::input('name', Input::post('name', isset($dtpsample) ? $dtpsample->name : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Name')); ?>
		</div>
		<div class="form-group">
		    <?php echo Form::label('DateTime', 'event_date', array('class'=>'control-label')); ?><br>
		    <input id="dtResult" size="20" type = "text" readonly/><br>   
		    <?php echo Form::input('event_date', Input::post('event_date', isset($dtpsample) ? $dtpsample->event_date : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'DateTime')); ?>
		</div>
		
		<div class="form-group">
			<label class='control-label'>&nbsp;</label>
			<?php echo Form::submit('submit', 'Save', array('class' => 'btn btn-primary')); ?>		</div>
	</fieldset>
<?php echo Form::close(); ?>
<h2>New dtpsample</h2>
<br>

<?php echo render('dtpsample/_form'); ?>


<p><?php echo Html::anchor('dtpsample', 'Back'); ?></p>
<h2>Editing dtsample</h2>
<br>

<?php echo render('dtpsample/_form'); ?>
<p>
	<?php echo Html::anchor('dtpsample/view/'.$dtpsample->id, 'View'); ?> |
	<?php echo Html::anchor('dtpsample', 'Back'); ?></p>
<h2>dtpsample</h2>
<br>
<?php if ($dtpsamples): ?>
<table class="table table-striped">
	<thead>
		<tr>
			<th>Name</th>
			<th>Event Date</th>
			<th></th>
		</tr>
	</thead>
	<tbody>
	    
<?php date_default_timezone_set('America/Chicago'); ?>	    
<?php foreach ($dtpsamples as $item): ?>		<tr>

			<td><?php echo $item->name; ?></td>
			<td><?php echo date('Y-m-d g:i:s A', $item->event_date); ?></td>
			
			<td>
				<?php echo Html::anchor('dtpsample/view/'.$item->id, 'View'); ?> |
				<?php echo Html::anchor('dtpsample/edit/'.$item->id, 'Edit'); ?> |
				<?php echo Html::anchor('dtpsample/delete/'.$item->id, 'Delete', array('onclick' => "return confirm('Are you sure?')")); ?>

			</td>
		</tr>
<?php endforeach; ?>	</tbody>
</table>

<?php else: ?>
<p>No dtsamples.</p>

<?php endif; ?><p>
	<?php echo Html::anchor('dtpsample/create', 'Add new dtsample', array('class' => 'btn btn-success')); ?>

</p>

Controller
fuel/app/classes/controller/dtpsample.php

<?php
class Controller_Dtpsample extends Controller_Template
{

    public $template = 'template_dtpsample';

	public function action_index()
	{
		$data['dtpsamples'] = Model_Dtpsample::find_all();
		$this->template->title = "DateTimePicker Sample";
		$this->template->content = View::forge('dtpsample/index', $data);

	}

	public function action_view($id = null)
	{
		is_null($id) and Response::redirect('dtpsample');

		$data['dtpsample'] = Model_Dtpsample::find_by_pk($id);

		$this->template->title = "DateTimePicker Sample";
		$this->template->content = View::forge('dtpsample/view', $data);

	}

	public function action_create()
	{
		if (Input::method() == 'POST')
		{
			$val = Model_Dtpsample::validate('create');

			if ($val->run())
			{
				$dtpsample = Model_Dtpsample::forge(array(
					'name' => Input::post('name'),
					'event_date' => Input::post('event_date')
				));

				if ($dtpsample and $dtpsample->save())
				{
					Session::set_flash('success', 'Added dtpsample #'.$dtpsample->id.'.');
					Response::redirect('dtpsample');
				}
				else
				{
					Session::set_flash('error', 'Could not save dtpsample.');
				}
			}
			else
			{
				Session::set_flash('error', $val->error());
			}
		}

		$this->template->title = "DateTimePicker Sample";
		$this->template->content = View::forge('dtpsample/create');

	}

	public function action_edit($id = null)
	{
		is_null($id) and Response::redirect('dtpsample');

		$dtpsample = Model_Dtpsample::find_one_by_id($id);

		if (Input::method() == 'POST')
		{
			$val = Model_Dtpsample::validate('edit');

			if ($val->run())
			{
				$dtpsample->name = Input::post('name');
                $dtpsample->event_date = Input::post('event_date');

				if ($dtpsample->save())
				{
					Session::set_flash('success', 'Updated dtpsample #'.$id);
					Response::redirect('dtpsample');
				}
				else
				{
					Session::set_flash('error', 'Nothing updated.');
				}
			}
			else
			{
				Session::set_flash('error', $val->error());
			}
		}

		$this->template->set_global('dtpsample', $dtpsample, false);
		$this->template->title = "DateTimePicker Sample";
		$this->template->content = View::forge('dtpsample/edit');

	}

	public function action_delete($id = null)
	{
		if ($dtpsample = Model_Dtpsample::find_one_by_id($id))
		{
			$dtpsample->delete();

			Session::set_flash('success', 'Deleted dtpsample #'.$id);
		}

		else
		{
			Session::set_flash('error', 'Could not delete dtpsample #'.$id);
		}

		Response::redirect('dtpsample');

	}

}

VBScript, Javascript for JSON from SQL Server

<meta http-equiv="x-ua-compatible" content="ie=9" /> 
<html>
      <head>
            <title>JSON from SQL Server</title>
            <hta:application
                  SINGLEINSTANCE="yes"
                  MAXIMIZEBUTTON="yes"
            >

            <script language="javascript">
                  try {
                    self.resizeTo(800, 400);
                   } catch(e) {
                   }
            </script>
            
      
<script language="VBscript">
	
Dim strSQL
    
Sub btnShowJSON()
  ProcessJSON(fnQueryData)
End Sub

function RStoJSON(rs)
    dim sFld,fld,sFlds
    dim sRec,sRecs
    dim sRecordSet
    dim lRecCnt

    sRecordSet = ""
    sRecs = ""
    lRecCnt = 0
    if rs.EOF or rs.BOF then
        RStoJSON = "null"
    else
        do while not rs.EOF and not rs.BOF
            lRecCnt = lRecCnt + 1
            sFlds = ""
            for each fld in rs.Fields
                sFld = """" & fld.Name & """:""" & fld.Value&"" & """"
                sFlds = sFlds & GetDelim(sFlds <> "","fld") & sFld
            next 
            sRec = "{" & sFlds & "}"
            sRecs = sRecs & GetDelim(sRecs <> "", "rec") & sRec
            rs.MoveNext
        loop
        sRecordSet = "( {""Records"": [" & vbCrLf & sRecs & vbCrLf & "], " 
        sRecordSet = sRecordSet & """RecordCount"":""" & lRecCnt & """ } )"
        RStoJSON = sRecordSet
    end if
end Function

' Return comma depending on condition and type fld or rec '
function GetDelim(bResult,sType)
    if bResult Then
        If sType = "fld" then
        GetDelim = ","
        End If
        If sType = "rec" Then
        GetDelim = "," & vbCrLf
        End if
    else
        GetDelim = ""
    end if
end function

Function fnQueryData()

Dim strJSON

Dim oCn,oRs1,strSQL

Set oCn = CreateObject( "ADODB.Connection" )
Set oRs1 = CreateObject( "ADODB.Recordset"  ) 

oCn.ConnectionString = "PROVIDER=SQLOLEDB" & ";Server=JEFFLD-HP\JD01SQL;Database=AdventureWorks2012;Trusted_Connection=Yes;"

oCn.open

strSQL = "select top 5 firstname,lastname,emailaddress from person.person P join person.emailaddress E on E.BusinessEntityID=P.BusinessEntityID"

oRs1.Open strSQL, oCn


strJSON = RStoJSON(oRS1)

' Clean up database resources
oRs1.Close
oCn.Close    
    
fnQueryData = strJSON    
    
End Function




</script>

<script language="javascript" type="text/javascript">
		
			function ProcessJSON(sJSON)
			{
			var rs = eval(sJSON);
			if ( rs ) { // has a non-null value
			  // get the record count
			  var str = rs.RecordCount + " Users:<br/>";
			  // get the data from the records
			  str = "<table border=1>"
			  for ( var recno = 0 ; recno < rs.RecordCount ; recno++ ) {
			    str += "<tr>";
			    str += "<td>"+rs.Records[recno].firstname + "</td>";
			    str += "<td>"+rs.Records[recno].lastname + "</td>";
			    str += "<td>"+rs.Records[recno].emailaddress + "</td>";
			    str += "</tr>";
			  }
			  str+= "</table>"
			  document.getElementById('userlist').innerHTML = str;
			  document.getElementById('json').innerHTML = sJSON;
			} else { // rs = null
			    str = "No users found"
			}
			}

	
</script>
             

</head>          
<body>
    <input type="button" name="btnShowJSON" id="btnShowJSON" value="Show JSON" onclick="btnShowJSON()"></input>
    <p></p>
    <div id="userlist"></div>
    <div id="json"></div>
</body>

</html>