生年月日2|既定値がある場合はselectedを追加

Demo

View&CSS3

Viewindex.ctpdownload

<div class="cake3_select_form_birthday2">

<?php

	echo "<select name=\"birth_year\">{$birth_year}</select>年<select name=\"birth_month\">{$birth_month}</select>月<select name=\"birth_day\">{$birth_day}</select>日";
?>
</div>

CSS3style.cssdownload

.cake3_select_form_birthday2 select{
	width: 4rem;
	outline: none;
	padding: 0.3rem 0;
	margin: 0 0.2rem 0 0.5rem;
	border: 1px solid #ccc;
}
.cake3_select_form_birthday2 select:first-child{
	margin-left: 0rem;
}

Controller

Controller.phpdownload

public function index(){

	// 使用している変数名
	// $selected_year, $selected_month, $selected_day, $birth_year, $birth_month, $birth_day
	// $i, $y_selected, $m_selected, $d_selected

	/* 既定値を設定 */
	$selected_year = "2020";//年

	$selected_month = "4";//月

	$selected_day = "10";//日

	/*----------------------------------------*/

	$birth_year = $birth_month = $birth_day = "<option value=\"\">--</option>";

	for($i = 1920; $i <= 2020; $i++){

		$y_selected = "";

		if($i == $selected_year){

			$y_selected = " selected";
		}

		$birth_year .= "<option value=\"{$i}\"{$y_selected}>{$i}</option>";
	}

	for($i = 1; $i <= 12; $i++){

		$i = sprintf('%02d', $i);

		$m_selected = "";

		if($i == $selected_month){

			$m_selected = " selected";
		}

		$birth_month .= "<option value=\"{$i}\"{$m_selected}>{$i}</option>";
	}

	for($i = 1; $i <= 31; $i++){

		$i = sprintf('%02d', $i);

		$d_selected = "";

		if($i == $selected_day){

			$d_selected = " selected";
		}

		$birth_day .= "<option value=\"{$i}\"{$d_selected}>{$i}</option>";
	}

	$this->set(compact('birth_year', 'birth_month', 'birth_day'));
}
© 2025 wayday