Yii2 Generated Calender Basic Code


(Auzadventure) #1

This is some of the snippets of a calender I did.

namespace common\models;

use yii\base\Model;
use yii\helpers\Url;


class JobsCalender extends Model {



public function tableHeader() {
	
	$dayA = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
	
	$s = '';
	foreach ($dayA as $day) {
		$s .= "<th> {$day}</th>";
	}
		
	return "<tr> {$s} </tr>"; 
	
}

public function getStartDate() {
	
	$date = date('Y-m-d',strtotime('today'));
	return $date;			
}

public function getEndDate() {
	$date = date('Y-m-d',strtotime('+ 30 days'));
	return $date; 
}


public function getCalStartDate() {
	
	$sDate = strtotime($this->getStartDate());
	
	$date = date('Y-m-d',strtotime('last monday',$sDate));
	return $date; 
}


public function getCalEndDate() {
	
	$sDate = strtotime($this->getEndDate());
	
	$date = date('Y-m-d',strtotime('sunday',$sDate));
	return $date; 
}


public function addDay($date) {
	$date = new \DateTime($date);	
	$date->modify('+1 day');
	return $date->format('Y-m-d');
}

public function getDay($date) {
	$date = new \DateTime($date);	
	return $date->format('j');
}	

public function genDay($date) {
	$day = $this->getDay($date);
	$dateUnix = strtotime($date);
	
	$class = '';

	if( $dateUnix < strtotime($this->getStartDate())) {
		$class = "disabled";
	}
	
	if( $dateUnix == strtotime($this->getStartDate())) {
		$class = "today";
	}

	if( $dateUnix > strtotime($this->getEndDate())) {
		$class = "disabled";
	}		

	$s = "<td class=\"{$class}\"> <span>{$day}</span> </td>";		
	return $s; 
}


public function genRows() {
	
	$start = $this->getCalStartDate();
	$end = $this->getCalEndDate();

	$s = "<tr>";
	
	$_date = $start; 
	$i=0;
	while (strtotime($_date) <= strtotime($end)) {
		$i++;
		
		$s .= $this->genDay($_date);
		$_date = $this->addDay($_date);
	
		if($i%7==0) {
			$s .=  "</tr> 
				    <tr>";
		}		
	}
	$s .= "</tr>";
	return $s;

}

}

Then in the view


$css = <<<CSS
.calender tr th {
   text-align:center;
   background-color: lightgrey;
   font-size:18px;
}
.calender tr td {
   text-align:center;
   font-size: 20px;
   padding: 20px !important;
}

.calender tr td.today {
   color: #fff;
   background-color: #ffb400; 
}


.calender tr td.disabled {
   color: #fff;
}

CSS;
$this->registerCss($css);

?>




<table class='table table-bordered calender'>

<?= $calenderM->tableHeader() ?>

<?= $calenderM->genRows() ?>

</table>```