редактирование точки

This commit is contained in:
Krivchikov Dmitry 2014-06-12 01:15:37 +04:00
parent 8b3307d6fa
commit a78328830a
7 changed files with 162 additions and 14 deletions

View File

@ -6,6 +6,7 @@ abstract class Controller
static $layout = 'layout.php'; static $layout = 'layout.php';
static private $styles = array(); static private $styles = array();
static private $scripts = array(); static private $scripts = array();
static private $vars = array();
static function addStyle($name) static function addStyle($name)
@ -24,6 +25,11 @@ abstract class Controller
} }
} }
static function addVar($name, $value)
{
self::$vars[$name] = $value;
}
/** /**
* Рендерит шаблон без лейаута. * Рендерит шаблон без лейаута.
* @param string $template - имя шаблона * @param string $template - имя шаблона
@ -75,6 +81,7 @@ abstract class Controller
'content' => $content, 'content' => $content,
'styles' => self::$styles, 'styles' => self::$styles,
'scripts' => self::$scripts, 'scripts' => self::$scripts,
'vars' => self::$vars,
'data' => $data, 'data' => $data,
), true); ), true);

View File

@ -100,6 +100,15 @@ class Model
} }
} }
/**
* Устанавливает значения полей из массива.
* @param array $values - ассоциативный массив со значениями.
*/
function setValues($values)
{
$this->_vals_ = $values;
}
/** /**
* Сохраняет объект в БД. * Сохраняет объект в БД.
* @return object/boolean * @return object/boolean

View File

@ -29,6 +29,7 @@ class IndexController extends Controller
$routes = $routes->getByAuthor(App::$user->id); $routes = $routes->getByAuthor(App::$user->id);
} }
self::addVar('isAdmin', (int)(App::$user && App::$user->isAdmin == 1) );
$res = App::$DB->query("SELECT COUNT(`id`) pointsCount FROM `points`")->fetch(PDO::FETCH_ASSOC); $res = App::$DB->query("SELECT COUNT(`id`) pointsCount FROM `points`")->fetch(PDO::FETCH_ASSOC);
App::setConfig('title', $res['pointsCount'].' или даже больше поводов не сидеть дома'); App::setConfig('title', $res['pointsCount'].' или даже больше поводов не сидеть дома');

View File

@ -39,7 +39,7 @@ class JsonController extends Controller
{ {
$point = new Point(); $point = new Point();
$point = $point->getByPK($id); $point = $point->getByPK($id);
$point->description = nl2br($point->description); $point->descriptionHtml = nl2br($point->description);
$categories = new Category(); $categories = new Category();
$categories = $categories->getAll(); $categories = $categories->getAll();
@ -82,11 +82,30 @@ class JsonController extends Controller
if(!( isset($_POST['lat']) && $_POST['lat'] )) $errors[6]='Ошибочное значение широты'; if(!( isset($_POST['lat']) && $_POST['lat'] )) $errors[6]='Ошибочное значение широты';
if(!( isset($_POST['lng']) && $_POST['lng'] )) $errors[7]='Ошибочное значение долготы'; if(!( isset($_POST['lng']) && $_POST['lng'] )) $errors[7]='Ошибочное значение долготы';
if(!App::$user ) $errors[8]='Вы не авторизованы! Пожалуйста, войдите.'; if(!App::$user ) $errors[8]='Вы не авторизованы! Пожалуйста, войдите.';
if(isset($_POST['id']) && $_POST['id'] && App::$user->isAdmin == 0 ) $errors[9]='Редактирование точек достурно только администратору!';
if (empty($errors)) if (empty($errors))
{ {
$point = new Point(); $point = new Point();
// Редактирование существующей точки
if (isset($_POST['id']) && $_POST['id'])
{
$id = $_POST['id'];
$point = $point->getByPK($id);
$point->setValues($_POST);
$point->save();
self::renderPartial('json.php', array(
'data' => $point->id
));
die;
}
$_POST['author'] = App::$user->id; $_POST['author'] = App::$user->id;
$_POST['date'] = time(); $_POST['date'] = time();
$point->add($_POST); $point->add($_POST);

View File

@ -15,6 +15,14 @@
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> <?php endif; ?>
<?php if ($vars): ?>
<script type="text/javascript">
<?php foreach ($vars as $varName => $var): ?>
var <?= $varName ?> = '<?= $var ?>';
<?php endforeach; ?>
</script>
<?php endif; ?>
</head> </head>
<body> <body>
<div class="header"> <div class="header">

View File

@ -5,7 +5,7 @@
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Добавление новой точки</h4> <h4 class="modal-title" id="myModalLabel">Добавление новой точки</h4>
</div> </div>
<div class="modal-body"> <div class="modal-body" style="padding-bottom: 0;">
<form method="POST" action="/json/addpoint/" id="addPointForm"> <form method="POST" action="/json/addpoint/" id="addPointForm">
<div class="form-group"> <div class="form-group">
<label class="control-label" for="name">Название</label> <label class="control-label" for="name">Название</label>
@ -42,6 +42,7 @@
Координаты: Координаты:
<input type="text" id="addPointLat" name="lat" class="form-control input-sm" style="width: 120px; display: inline-block;" readonly="readonly" disabled="disabled"/> <input type="text" id="addPointLat" name="lat" class="form-control input-sm" style="width: 120px; display: inline-block;" readonly="readonly" disabled="disabled"/>
<input type="text" id="addPointLng" name="lng" class="form-control input-sm" style="width: 120px; display: inline-block;" readonly="readonly" disabled="disabled"/> <input type="text" id="addPointLng" name="lng" class="form-control input-sm" style="width: 120px; display: inline-block;" readonly="readonly" disabled="disabled"/>
<button type="button" class="btn btn-sm btn-default" onclick="editSetNewCoords();"><span class="glyphicon glyphicon-flag"></span></button>
</div> </div>
</form> </form>
</div> </div>

View File

@ -2,10 +2,44 @@
* Let's GO! * Let's GO!
*/ */
// ------------ Система статусов приложения ------------------------------------
var statusReady = 0; // Обычный режим. Просмотр точек, навигация по карте и прочее.
var statusHunting = 1; // Курсор-прицел. Поиск места для добавления точки.
var statusReHunting = 2; // КУрсор прицел. Переопределение координат точки.
var statusAdd = 3; // Открыто окно добавления точки - форма.
var statusEdit = 4; // Открыто окно редактирования точки. В нём информация о существующей точке, включая ID.
var statusSendingToServer = 5; // Отправлен запрос на сервер - ждём, не даём жать кнопку повторно, отвлекаем пользователя.
var status = statusReady;
var statusPrev = statusReady;
/**
* Устанавливает новое значение статуса.
* @returns {undefined}
*/
function setStatus(value)
{
statusPrev = status;
status = value;
}
/**
* Меняет значение статуса на предыдущее.
* @returns {undefined}
*/
function resetStatus()
{
tmp = status;
status = statusPrev;
statusPrev = tmp;
}
// -----------------------------------------------------------------------------
ymaps.ready(init); ymaps.ready(init);
var myMap; var myMap;
var categories; var categories;
var points = Array(); var points = Array();
var pointsSources = Array();
var search; var search;
var route = false; var route = false;
var addPointInProcess = false; var addPointInProcess = false;
@ -68,11 +102,27 @@ function init() {
myMap.events.add('click', function(e) { myMap.events.add('click', function(e) {
if (!myMap.balloon.isOpen()) { if (!myMap.balloon.isOpen()) {
if ($('#addPointButton').hasClass('btn-success')) if (status == statusHunting)
{ {
coords = e.get('coordPosition'); coords = e.get('coordPosition');
$('#addPointId').remove();
$('#addPointForm input').val('');
$("#addPointCategoryId option" ).attr('selected', null);
$('#addPointLat').val(coords[0].toPrecision(11)); $('#addPointLat').val(coords[0].toPrecision(11));
$('#addPointLng').val(coords[1].toPrecision(11)); $('#addPointLng').val(coords[1].toPrecision(11));
$('#myModalLabel').text('Добавление новой точки');
$('#addPointModal').modal('show');
} else if (status == statusReHunting)
{
resetStatus();
coords = e.get('coordPosition');
$('#addPointLat').val(coords[0].toPrecision(11));
$('#addPointLng').val(coords[1].toPrecision(11));
$('#myModalLabel').text('Редактирование точки');
$('#addPointModal').modal('show'); $('#addPointModal').modal('show');
} }
} }
@ -183,14 +233,27 @@ function showInfo(id)
$.ajax({ $.ajax({
url: "/json/point/id/" + id, url: "/json/point/id/" + id,
success: function(data) { success: function(data) {
pointsSources[id] = data;
description = '<div class="infoCard">' + description = '<div class="infoCard">' +
'<h3>' + data.name + '</h3>' + '<h3>' + data.name + '</h3>' +
'<img src="' + data.img + '" />' + '<img src="' + data.img + '" />' +
'<button type="button" class="btn btn-default btn-xs" onclick="addToRoute(' + id + ')">' + '<button type="button" class="btn btn-default btn-xs" onclick="addToRoute(' + id + ')">' +
'<span class="glyphicon glyphicon-plus"></span> Добавить в маршрут' + '<span class="glyphicon glyphicon-plus"></span> Добавить в маршрут' +
'</button><br/>' + '</button><br/>';
data.description +
' <a href="' + data.source + '" target="blank">Подробнее...</a></div>' if (isAdmin == '1')
{
description = description + '<button type="button" class="btn btn-default btn-xs" onclick="editPoint(' + id + ')">' +
'<span class="glyphicon glyphicon-pencil"></span> Редактировать' +
'</button><br/>';
}
description = description + data.descriptionHtml;
if (data.source.length > 11)
description = description + ' <a href="' + data.source + '" target="blank">Подробнее...</a>';
description = description + '</div>';
points[id].properties.set('balloonContent', description); points[id].properties.set('balloonContent', description);
point = getURLParameter('point'); point = getURLParameter('point');
@ -262,23 +325,30 @@ function activateAddPoint()
{ {
$('#addPointButton').toggleClass('btn-success').toggleClass('btn-default'); $('#addPointButton').toggleClass('btn-success').toggleClass('btn-default');
if ($('#addPointButton').hasClass('btn-success')) if ($('#addPointButton').hasClass('btn-success'))
{
myMap.cursors.push('crosshair'); myMap.cursors.push('crosshair');
setStatus(statusHunting)
}
else else
{
myMap.cursors.push('arrow'); myMap.cursors.push('arrow');
setStatus(statusReady)
}
return true; return true;
} }
/** /**
* Отправляет данные по новой точке на сервер. * Отправляет данные о точке на сервер.
* @returns {Boolean} * @returns {Boolean}
*/ */
function addPoint() function addPoint()
{ {
$('.form-group').removeClass('has-error'); $('.form-group').removeClass('has-error');
if (!addPointInProcess) if (status != statusSendingToServer)
{ {
addPointInProcess = true; setStatus(statusSendingToServer)
id = $('#addPointId').length ? $('#addPointId').val() : 0;
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/json/addpoint/", url: "/json/addpoint/",
@ -289,13 +359,20 @@ function addPoint()
categoryId: $('#addPointCategoryId').val(), categoryId: $('#addPointCategoryId').val(),
source: $('#addPointSource').val(), source: $('#addPointSource').val(),
lat: $('#addPointLat').val(), lat: $('#addPointLat').val(),
lng: $('#addPointLng').val() lng: $('#addPointLng').val(),
id: id
}, },
success: function(data) { success: function(data) {
balloon = myMap.balloon.open([$('#addPointLat').val(), $('#addPointLng').val()], {content: 'Точка успешно добавлена!'}, {closeButton: false}); text = id ? 'Точка успешно отредактирована!' : 'Точка успешно добавлена!';
if ( id )
{
myMap.geoObjects.remove(points[id]);
}
balloon = myMap.balloon.open([$('#addPointLat').val(), $('#addPointLng').val()], {content: text}, {closeButton: false});
setTimeout(function() { setTimeout(function() {
balloon.close(); balloon.close();
}, 3000); }, 2000);
obj = {}; obj = {};
obj.id = data; obj.id = data;
@ -315,9 +392,10 @@ function addPoint()
$('#addPointForm textarea').val(''); $('#addPointForm textarea').val('');
$('.form-group').removeClass('has-error'); $('.form-group').removeClass('has-error');
$('#addPointButton').removeClass('btn-success').addClass('btn-default'); $('#addPointButton').removeClass('btn-success').addClass('btn-default');
$('#addPointId').remove();
myMap.cursors.push('arrow'); myMap.cursors.push('arrow');
setStatus(statusReady);
addPointInProcess = false;
return true; return true;
}, },
error: function(data) { error: function(data) {
@ -341,7 +419,7 @@ function addPoint()
if (message != '') if (message != '')
alert(message); alert(message);
addPointInProcess = false; resetStatus();
return false; return false;
} }
}); });
@ -499,3 +577,28 @@ function routeToURL()
return true; return true;
} }
function editPoint(id)
{
$('#addPointId').remove();
$('<input type="hidden" id="addPointId" name="id"/>').appendTo('#addPointForm').val(id);
$('#addPointName').val(pointsSources[id].name);
$('#addPointImg').val(pointsSources[id].img);
$('#addPointDescription').val(pointsSources[id].description);
$("#addPointCategoryId option" ).attr('selected', null);
$("#addPointCategoryId option[value='"+pointsSources[id].categoryId+"']" ).attr('selected', 'selected');
$('#addPointSource').val(pointsSources[id].source);
$('#addPointLat').val(pointsSources[id].lat);
$('#addPointLng').val(pointsSources[id].lng);
myMap.balloon.close();
$('#addPointModal').modal('show');
setStatus(statusEdit);
}
function editSetNewCoords()
{
$('#addPointModal').modal('hide');
myMap.cursors.push('crosshair');
setStatus(statusReHunting)
}