Непередаваемое ощущение .... и ты понимаешь, что сделал это своими руками.
class Database {
private $mysqli;
public function __construct(){
$dsn = "mysql:host=localhost;dbname=banan165_database";
$this->mysqli = new PDO($dsn, "root", "");
}
public function query($sql){
return $this->mysqli->query($sql);
}
}
$db = new Database();
$db->query("INSERT INTO categories(name) VALUES('PDO')");
date('d.m', strtotime('2019-09-11'))
(new DateTimeImmutable('2019-09-11'))->format('d.m')
public function getPromotion(): ?Promotion
{
return new Promotion($this->promotion_id, $this->promotion_time);
}
public function isPromoted(): bool
{
return $this—>getPromotion()->isPromoted()
}
public function isPromoted(): bool
{
return $this->getPromotion() ? $this—>getPromotion()->isPromoted() : false
}
class Customer extends ActiveRecord
{
public function getOrders()
{
return $this->hasMany(Order::className(), ['customer_id' => 'id']);
}
}
class Order extends ActiveRecord
{
public function getCustomer()
{
return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
}
}
// SELECT * FROM `customer` WHERE `id` = 123
$customer = Customer::findOne(123);
// SELECT * FROM `order` WHERE `customer_id` = 123
// $orders - это массив объектов Order
$orders = $customer->orders;
<div id="map"></div>
<?php
$js = <<< JS
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
JS;
$this->registerJs( $js, $position = yii\web\View::POS_READY, $key = null );
?>
<?php
$js = <<< JS
var autocompletes, marker, infowindow, map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
map: map
});
// адрес откуда
var inputs = document.querySelector('#place_departure');
autocompletes = new google.maps.places.Autocomplete(inputs);
google.maps.event.addListener(autocompletes, 'place_changed', function () {
marker.setVisible(false);
infowindow.close();
var place = autocompletes.getPlace();
if (!place.geometry) {
window.alert("No details available for input: '" + place.name + "'");
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setIcon(({
url: place.icon,
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var place_departure = '';
if (place.address_components) {
place_departure = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + place_departure);
infowindow.open(map, marker);
});
}
JS;
$this->registerJs( $js, $position = yii\web\View::POS_READY, $key = null );
?>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
if ($model->validate()) {
///здесь ваш код
$model->save()
пишем данные, закрываем модалку
} else {
выводим результат валидации (рендерим аякс? или встроенная валидация?)
}
}
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
///code
$model->save()
}
Вопрос: как мне в контроллере проверить, что была нажата кнопка Save в форме?
$customer = Customer::findOne(123);
$order = new Order();
$order->subtotal = 100;
// ...
// установка атрибута, которой задаёт связь "customer" в объекте Order
$order->customer_id = $customer->id;
$order->save();
if($model->load(Yii::$app->request->post()) && $address->load(Yii::$app->request->post())){
$transaction = Yii::$app->db->beginTransaction();
try {
if ($model->save()) {
$address->user_id = $model->id
Yii::$app->session->setFlash('success', 'Model save');
$address->save();
$transaction->commit();
Yii::$app->session->setFlash('success', 'User added');
return $this->refresh();
} else {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error');
}
} catch (Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error2222');
}
}
$customer = Customer::findOne(123);
$order = new Order();
$order->subtotal = 100;
// ...
$order->link('customer', $customer);
if($model->load(Yii::$app->request->post()) && $address->load(Yii::$app->request->post())){
$transaction = Yii::$app->db->beginTransaction();
try {
if ($model->save()) {
$address->link('nameRelationModel', $model)
Yii::$app->session->setFlash('success', 'Model save');
$address->save();
$transaction->commit();
Yii::$app->session->setFlash('success', 'User added');
return $this->refresh();
} else {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error');
}
} catch (Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error2222');
}
}
$models = $query->offset($pages->offset)
->limit($pages->limit)
->all();