not able to create the record in yii json api - yii

I am trying to learn yii and create an api. I am able to get the data but I am not able to create new record using my json object.
This is what I get
Here is my main.php in api config looks like
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'api\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
'user' => [
'identityClass' => '\common\models\User',
'enableSession' => false,
'loginUrl' => null
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'AH7T3J6-nwgUOF3DK_MYPhyzhhguo5-k',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
],
'params' => $params,
];
As you can see I am setting up the json parser in request.
Here is the model
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "room".
*
* #property integer $id
* #property integer $floor
* #property integer $room_number
* #property integer $has_conditioner
* #property integer $has_tv
* #property integer $has_phone
* #property string $available_from
* #property string $price_per_day
* #property string $description
*/
class Room extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'room';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['floor', 'room_number', 'has_conditioner', 'has_tv', 'has_phone', 'available_from'], 'required'],
[['floor', 'room_number', 'has_conditioner', 'has_tv', 'has_phone'], 'integer'],
[['available_from'], 'safe'],
[['price_per_day'], 'number'],
[['description'], 'string'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'floor' => 'Floor',
'room_number' => 'Room Number',
'has_conditioner' => 'Has Conditioner',
'has_tv' => 'Has Tv',
'has_phone' => 'Has Phone',
'available_from' => 'Available From',
'price_per_day' => 'Price Per Day',
'description' => 'Description',
];
}
}
For some reason its just not getting the json format.
I tried with form-data and it seems to work. But just raw json wont work
please have a look here

Related

EasyAdmin 3 Symfony 5 CrudController AssociationField

I'm using EasyAmdin 3 with Symfony 5 and I have a OneToMany relation between Challenge and Encadrement. Defined In Challenge.php:
/**
* #ORM\OneToMany(targetEntity=Encadrement::class, mappedBy="challengePartner")
*/
private $bornes;
I made a CRUDController for Challenge, and I want to be able to add Encadrement directly when creating/editing a Challenge. I did this :
AssociationField::new('bornes'),
I can choose between all the Encadrement already created. But what I want is to be able to multiple add Encadrement and I can't find how to do this. I tried making my own EncadrementType :
class EncadrementType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, array(
"label" => "Nom"
))
->add('low', IntegerType::class, array(
"label" => "Borne basse"
))
->add('high', IntegerType::class, array(
"label" => "Borne haute"
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Encadrement::class,
]);
}
}
And something like this in the ChallengeCRUD:
AssociationField::new('bornes')->setFormType(EncadrementType::class),
But I get this error when I don't even use those options:
An error has occurred resolving the options of the form "App\Form\EncadrementType": The options "class", "multiple", "query_builder" do not exist. Defined options are: "action", "allow_extra_fields", "allow_file_upload", "attr", "attr_translation_parameters", "auto_initialize", "block_name", "block_prefix", "by_reference", "compound", "constraints", "csrf_field_name", "csrf_message", "csrf_protection", "csrf_token_id", "csrf_token_manager", "data", "data_class", "disabled", "ea_crud_form", "empty_data", "error_bubbling", "error_mapping", "extra_fields_message", "getter", "help", "help_attr", "help_html", "help_translation_parameters", "inherit_data", "invalid_message", "invalid_message_parameters", "is_empty_callback", "label", "label_attr", "label_format", "label_html", "label_translation_parameters", "legacy_error_messages", "mapped", "method", "post_max_size_message", "property_path", "required", "row_attr", "setter", "translation_domain", "trim", "upload_max_size_message", "validation_groups".
I tried adding the multiple option to the AssociationField but it does nothing:
AssociationField::new('bornes')->setFormTypeOption("multiple","true"),
I'm stuck there, thanks for any help !
Try CollectionField like this:
<?php
yield CollectionField::new('bornes')
->setFormTypeOptions([
'delete_empty' => true,
'by_reference' => false,
])
->setEntryIsComplex(false)
->setCustomOptions([
'allowAdd' => true,
'allowDelete' => true,
'entryType' => EncadrementType::class,
'showEntryLabel' => false,
])
;

Setting unknown property: yii\validators\NumberValidator::0

I try to call a setting form, which shows input forms for saving data into price database.
My model throws the above Exception during rendering:
Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: yii\validators\NumberValidator::0
error in line of _price-item:
$form->field($model, "[{$i}]credits")->textInput(['maxlength' => 8])
Model:
<?php
namespace app\models;
use Yii;
/**
* #package app\models
*
* #property integer $id
* #property integer $credits
* #property integer $price
* #property integer $reduced_price
* #property integer $discount
* #property string $start
* #property string $end
* #property integer $active
*/
class Price extends \app\base\ActiveRecord
{
public function rules()
{
return [
[['credits'], 'integer', 'required'],
[['price'], 'integer','integerOnly' => false,'required', 'min' => 0, 'max' => 10000],
[['reduced_price','discount'],'integer','integerOnly' => false,'min' => 0, 'max' => 10000],
[['start','end'],'format' => 'php:Y-m-d H:i:s'],
[['active'], 'integer'],
[['active'], 'in', 'range' => array_keys(self::$_CONDITIONS)],
];
}
}
Widget:
<?php DynamicFormWidget::begin([
'widgetContainer' => 'wrapper-prices',
'widgetBody' => '.container-items',
'widgetItem' => '.item',
'limit' => 30,
'min' => 1,
'insertButton' => '.add-item',
'deleteButton' => '.remove-item',
'model' => count($prices) ? $prices[0] : new \app\models\Price(),
'template' => $this->render('_price-item', [
'i' => 0,
'form' => $form,
'model' => count($prices) ? $prices[0] : new \app\models\Price(),
]),
'formId' => 'dynamic-form',
'formFields' => [
'credits',
'price',
'reduced_price',
'discount',
'start',
'end',
'active',
],
]); ?>
mysql:
CREATE TABLE `price` (
`id` int(11) NOT NULL,
`credits` int(11) NOT NULL,
`price` float NOT NULL,
`reduced_price` float DEFAULT NULL,
`discount` float DEFAULT NULL,
`start` datetime DEFAULT NULL,
`end` datetime DEFAULT NULL,
`active` smallint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Can anybody tell me, what is wrong ?
my head almost burns
It's your first 2 rules
[['credits'], 'integer', 'required'],
[['price'], 'integer','integerOnly' => false,'required', 'min' => 0, 'max' => 10000],
You are setting 2 core validators integer , required in one rule which is wrong. The integer for example validator takes max or min parameters and that too as an associative array 'min'=>10,and assigns the property values like $obj->min=10, and your code would force the integer validator to interpret 'required' as 0=>'required' , which clearly explains the error above.
Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: yii\validators\NumberValidator::0
Chang you rules method to
public function rules()
{
return [
[['credits','price'], 'required'],
[['price'], 'integer','integerOnly' => false, 'min' => 0, 'max' => 10000],
[['reduced_price','discount'],'integer','integerOnly' => false,'min' => 0, 'max' => 10000],
[['start','end'],'datetime','format' => 'php:Y-m-d H:i:s'],
[['active','credits'], 'integer'],
[['active'], 'in', 'range' => array_keys(self::$_CONDITIONS)],
];
}
Update
Your 4th rule will also be throwing error should be
[['start','end'],'datetime','format' => 'php:Y-m-d H:i:s'],
I have updated the code block above too.
the correct working rule is:
Thanks to Muhammad
public function rules()
{
return [
[['credits','price'], 'required'],
[['price','reduced_price','discount'],'integer','integerOnly' => false,'min' => 0, 'max' => 10000],
[['start','end'],'datetime','format' => 'php:Y-m-d'],
[['status','credits'], 'integer'],
[['status'], 'in', 'range' => array_keys(self::$_CONDITIONS)],
];
}

Laravel 5.8 LDAP Authentication not working - LdapRecord Package

I'm trying to implements an LDAP authentication in an application for my company. I'm using Laravel 5.8 and the LdapRecord package
I have succeed to connect the application with the LDAP server test see Successfully connected and my to authenticate with openldap to online server its also Successfully. but when i want to do the authentication with active directory to my app it not working , Why who can help me?
Here is my code :
The .env
LDAP_LOGGING=true
LDAP_CONNECTION=default
LDAP_HOST=server
LDAP_PORT=389
LDAP_BASE_DN="dc=mydomain,dc=local"
LDAP_TIMEOUT=5
LDAP_SSL=false
LDAP_TLS=false
The ldap.php
return [
'default' => env('LDAP_CONNECTION', 'default'),
'connections' => [
'default' => [
'hosts' => [env('LDAP_HOST', 'server')],
'username' => env('LDAP_USERNAME', ''),
'password' => env('LDAP_PASSWORD', ''),
'port' => env('LDAP_PORT', 389),
'base_dn' => env('LDAP_BASE_DN', 'dc=mydomain,dc=local'),
'timeout' => env('LDAP_TIMEOUT', 5),
'use_ssl' => env('LDAP_SSL', false),
'use_tls' => env('LDAP_TLS', false),
],
],
'logging' => env('LDAP_LOGGING', true),
'cache' => [
'enabled' => env('LDAP_CACHE', false),
'driver' => env('CACHE_DRIVER', 'file'),
],
];
The auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'ldap',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent' ,
'model' => App \ User :: class,
],
'ldap' => [
'driver' => 'ldap',
'model' => LdapRecord\Models\ActiveDirectory\User::class,
// 'model' => LdapRecord\Models\OpenLDAP\User::class,
'database' => [
'model' => App\User::class,
'sync_passwords' => false,
'sync_attributes' => [
'name' => 'cn',
'email' => 'mail',
],
],
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
The user.php model
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use LdapRecord\Laravel\Auth\LdapAuthenticatable;
use LdapRecord\Laravel\Auth\AuthenticatesWithLdap;
class User extends Authenticatable implements LdapAuthenticatable
{
use Notifiable, AuthenticatesWithLdap, HasLdapUser ;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password', 'remember_token' ,
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
The LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function credentials(Request $request)
{
return [
'uid' => $request->get('username'),
'password' => $request->get('password'),
];
}
public function username()
{
return 'username';
}
}
Is there anyone who has already used this package and can help me on my code ? thank you in advance :)

Connecting Frontend to backend when login

i have a code in Yii2 advanced template, i want to make a link when i log in from frontend then connecting in backend and when i logout from backend it back to frontend,how can i make that?
and this is my comon/config/main.php file
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
//'class' => 'yii\web\urlManager',
'enablePrettyUrl' => false,
'showScriptName' => true,
'baseUrl' => '/backend/web',
],
'urlManagerFrontEnd' => [
'class' => 'yii\web\urlManager',
'baseUrl' => '/frontend/web',
'enablePrettyUrl' => false,
'showScriptName' => true,
]
],
];
and this is my siteController in frontend
<?php
namespace frontend\controllers;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Url;
use backend;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* #return mixed
*/
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* #return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* #return mixed
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* #return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
/**
* Signs user up.
*
* #return mixed
*/
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
/**
* Requests password reset.
*
* #return mixed
*/
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
/**
* Resets password.
*
* #param string $token
* #return mixed
* #throws BadRequestHttpException
*/
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->session->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
/*public function goBack($defaultUrl = null)
{
if(is_null($defaultUrl)) {
$defaultUrl = Yii::$app->request->baseUrl; // ganti dibagian ini ndu
}
return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
}*/
}
and the same with siteController in backend

FOSRestBundle post many to one relation

I would like to know how to properly post data when Entity has another ManyToOne relation in FOSRestBundle.
User entity has locale (locale_id):
/**
* #ORM\ManyToOne(targetEntity="Locale")
* #ORM\JoinColumn(name="locale_id", referencedColumnName="id")
*/
private $locale;
I was hoping that passing something like:
{
"user":{
"firstName":"John",
"emailAddress":"somewhere#somehow.com",
"lastName":"Doe",
"sex":"1",
"locale":{
"id":"1"
}
}
}
will work, but it does not pass the validation and Symfony throws:
{"code":400,"message":"Validation Failed","errors":{"children":{"firstName":[],"lastName":[],"emailAddress":[],"sex":[],"locale":{"errors":["This value is not valid."]}}}}
As you can see, locale is still wrong.
Does anyone know how can I post it properly?
EDIT
Here is how the form looks like:
<?php
namespace Software\Bundle\Form\Type;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* Class UserType
* #package Software\Bundle\Form\Type
*/
class UserType extends AbstractFormType
{
public function buildForm(FormBuilderInterface $builder, array $option)
{
$builder
->add('firstName', 'text', [
'label' => 'word.first_name',
'required' => true
])
->add('lastName', 'text', [
'label' => 'word.last_name',
'required' => true
])
->add('emailAddress', 'email', [
'label' => 'word.email_address',
'required' => true
])
->add('sex', 'choice', [
'label' => 'word.sex',
'choices' => [
'0' => 'word.male',
'1' => 'word.female'
],
'required' => true,
'empty_value' => 'word.select',
'empty_data' => null
])
->add('locale', 'entity', [
'label' => 'word.locale',
'required' => false,
'property' => 'code',
'class' => 'SoftwareBundle:Locale',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('l')
->orderBy('l.code', 'ASC');
},
'placeholder' => 'word.select',
'empty_data' => null
])
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'translation_domain' => 'general',
'data_class' => 'Software\Bundle\Entity\User',
'attr' => ['novalidate' => 'novalidate'],
'csrf_protection' => false
]);
}
public function getName()
{
return 'user';
}
}
EDIT 2
And the controller:
public function postAction(Request $request)
{
$form = $this->createForm(new UserType(), new User());
$form->handleRequest($request);
if($form->isValid())
{
die('are you valid or not??');
}
return $this->view($form, 400);
}
Try without the "1" and only with 1 , otherwise it can be interpreted as string.
Edit :
{
"user":{
"firstName":"John",
"emailAddress":"somewhere#somehow.com",
"lastName":"Doe",
"sex":"1",
"locale": 1
}
}
}