Display coupon code customized fields values in edit page in Woocommerce - database

Eveybody,
I'm sorry if the answer is very simple, i'm a student, but i've a problem with my custom coupon field in the edit page page in Woocommerce.
i'd search so long time but the answer was for display coupon in order or checkout ...
i've created 4 new fields in the coupon, i can store them and i can validate in the cart, ecreything is fine, except one thing.
I'can't display the data already saved in the edit coupon page.
For a better UX, i would display them in the input created.
SomeOne can help me please ?
// This my class
public function __construct()
{
$this->removeHooks();
add_action('woocommerce_coupon_options_usage_restriction', [$this, 'ajoutPeriode'], 10, 2);
add_action('woocommerce_coupon_options_usage_restriction', [$this, 'ajoutDuree'], 20, 2);
add_action('woocommerce_coupon_options_save', [$this, 'saveAjoutPeriode'], 10, 2);
add_action('woocommerce_coupon_options_save', [$this, 'saveAjoutDuree'], 20, 2);
add_action('woocommerce_coupon_is_valid', [$this, 'isValidCode'], 100, 2);
add_action( 'add_meta_boxes', [$this, 'addCustomCouponFieldOnEdit']);
}
/**
* Fonction qui ajoute un champ periode de voyage dans les codes promos
*
* #version 1.0.0
* #author Marie N
* #param [type] $coupon_get_id
* #param WC_Coupon $coupon
* #return void
*/
public function ajoutPeriode($coupon_get_id, WC_Coupon $coupon)
{
include locate_template('templates/parts/post/champPeriodeVoyage.php');
}
/**
* fonction qui ajoute un champ durée dans les codes promos
*
* #version 1.0.0
* #author Marie N
* #param [type] $coupon_get_id
* #param WC_Coupon $coupon
* #return void
*/
public function ajoutDuree($coupon_get_id, WC_Coupon $coupon)
{
include locate_template('templates/parts/post/champDureeVoyage.php');
var_dump($coupon);
}
/**
* Sauvegarde en base les données dans les nouveaux champs
*
* #version 1.0.0
* #author Marie N
* #param [type] $post_id
* #param [type] $coupon
* #return void
*/
public function saveAjoutPeriode($post_id, $coupon)
{
if (isset($_POST['restriction_time_start']))
update_post_meta($post_id, 'restriction_time_start', $_POST['restriction_time_start']);
if (isset($_POST['restriction_time_end']))
update_post_meta($post_id, 'restriction_time_end', $_POST['restriction_time_end']);
}
/**
* sauvegarde les données du champ en base
*
* #version 1.0.0
* #author Marie N
* #param [type] $post_id
* #param [type] $coupon
* #return void
*/
public function saveAjoutDuree($post_id, $coupon)
{
if (isset($_POST['time_travel_start']))
update_post_meta($post_id, 'time_travel_start', $_POST['time_travel_start']);
if (isset($_POST['time_travel_end']))
update_post_meta($post_id, 'time_travel_end', $_POST['time_travel_end']);
}
/**
* Verification de la validité du code promo
*
* #version 1.0.0
* #author Marie N
* #param [type] $is_valid
* #param [type] $coupon
* #return boolean
*/
public function isValidCode($is_valid, $coupon)
{
$contenuPanier = WC()->cart->get_cart();
// var_dump($contenuPanier);
foreach (WC()->cart->get_cart() as $cart_item) {
$dateReservationDebut = $cart_item['rental_data']['pickup_date'];
$dateReservationFin = $cart_item['rental_data']['dropoff_date'];
$nombreJoursReserves = $cart_item['rental_data']['days'];
}
$datePeriodeDebut = get_post_meta($coupon->get_id(), 'restriction_time_start', true);
$datePeriodeFin = get_post_meta($coupon->get_id(), 'restriction_time_end', true);
$dateDureeMin = get_post_meta($coupon->get_id(), 'time_travel_start', true);
$dateDureeMax = get_post_meta($coupon->get_id(), 'time_travel_end', true);
if ($dateReservationDebut < $datePeriodeDebut && $dateReservationDebut > $datePeriodeFin) return;
if ($dateReservationFin < $datePeriodeDebut && $dateReservationFin > $datePeriodeFin) return;
if ($nombreJoursReserves < $dateDureeMin && $nombreJoursReserves > $dateDureeMax) return;
return $is_valid;
}
// below is my field template for adding a reservation date
<div class="options-group">
<?php woocommerce_form_field(
'restriction_time_start',
[
'type' => 'date',
'name' => 'restriction-time_start',
'class' => ['form-field'],
'label' => 'Période de réservation début',
]
);
woocommerce_form_field(
'restriction_time_end',
[
'type' => 'date',
'name' => 'restriction-time-end',
'class' => ['form-field'],
'label' => 'Période de réservation fin',
'placeholder' => '',
]
)
?>
It's my first question on stackoverflow, i'm a little bit scared ^^
If you need more information, ask me, especially my code is in Fran-glish, sorry about that !
Tkhs

Related

User Transformer::$availableIncludes must be array

I am using Laravel 6.20 version with php version 8 get this error when call the user transfomer
here is my code
model class
<?php
namespace App\Models;
use Carbon\Carbon;
use App\Models\Country;
use App\Models\Access\Role;
use App\Models\Admin\Staff;
use App\Models\Admin\Driver;
use App\Models\Admin\Owner;
use App\Models\Request\Request;
use App\Models\Master\Developer;
use App\Models\Master\PocClient;
use App\Models\Traits\HasActive;
use App\Models\Admin\AdminDetail;
use App\Models\Admin\UserDetails;
use App\Models\Payment\UserWallet;
use Laravel\Passport\HasApiTokens;
use App\Models\LinkedSocialAccount;
use App\Models\Payment\DriverWallet;
use App\Base\Services\OTP\CanSendOTP;
use App\Models\Traits\DeleteOldFiles;
use App\Models\Traits\UserAccessTrait;
use Illuminate\Support\Facades\Storage;
use Illuminate\Notifications\Notifiable;
use App\Models\Payment\UserWalletHistory;
use App\Models\Traits\HasActiveCompanyKey;
use App\Models\Traits\UserAccessScopeTrait;
use App\Base\Services\OTP\CanSendOTPContract;
use Nicolaslopezj\Searchable\SearchableTrait;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Models\Request\FavouriteLocation;
class User extends Authenticatable implements CanSendOTPContract
{
use CanSendOTP,
DeleteOldFiles,
HasActive,
HasApiTokens,
Notifiable,
UserAccessScopeTrait,
UserAccessTrait,
SearchableTrait,
HasActiveCompanyKey;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'username', 'email', 'password', 'mobile', 'country', 'profile_picture', 'email_confirmed', 'mobile_confirmed', 'email_confirmation_token', 'active','fcm_token','login_by','apn_token','timezone','rating','rating_total','no_of_ratings','refferal_code','referred_by','social_nickname','social_id','social_token','social_token_secret','social_refresh_token','social_expires_in','social_avatar','social_avatar_original','social_provider','company_key','lang'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token', 'email_confirmation_token',
];
/**
* The attributes that have files that should be auto deleted on updating or deleting.
*
* #var array
*/
public $deletableFiles = [
'profile_picture',
];
/**
* The attributes that can be used for sorting with query string filtering.
*
* #var array
*/
public $sortable = [
'id', 'name', 'username', 'email', 'mobile', 'profile_picture', 'last_login_at', 'created_at', 'updated_at',
];
/**
* The relationships that can be loaded with query string filtering includes.
*
* #var array
*/
public $includes = [
'roles', 'otp','requestDetail'
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
];
/**
* Get the Profile image full file path.
*
* #param string $value
* #return string
*/
// public function getProfilePictureAttribute($value)
// {
// if (empty($value)) {
// $default_image_path = config('base.default.user.profile_picture');
// return env('APP_URL').$default_image_path;
// }
// return Storage::disk(env('FILESYSTEM_DRIVER'))->url(file_path($this->uploadPath(), $value));
// }
public function getProfilePictureAttribute($value)
{
if (!$value) {
$default_image_path = config('base.default.user.profile_picture');
return env('APP_URL').$default_image_path;
}
return Storage::disk(env('FILESYSTEM_DRIVER'))->url(file_path($this->uploadPath(), $value));
}
/**
* Override the "boot" method of the model.
*
* #return void
*/
public static function boot()
{
parent::boot();
// Model event handlers
}
/**
* Set the password using bcrypt hash if stored as plaintext.
*
* #param string $value
*/
public function setPasswordAttribute($value)
{
$this->attributes['password'] = (password_get_info($value)['algo'] === 0) ? bcrypt($value) : $value;
}
/**
* The roles associated with the user.
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles()
{
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
}
/**
* The OTP associated with the user's mobile number.
*
* #return \Illuminate\Database\Eloquent\Relations\hasOne
*/
public function otp()
{
return $this->hasOne(MobileOtp::class, 'mobile', 'mobile');
}
/**
* Get the user model for the given username.
*
* #param string $username
* #return \Illuminate\Database\Eloquent\Model|null|static
*/
public function findForPassport($username)
{
return $this->where($this->usernameField($username), $username)->first();
}
/**
* Get the username attribute based on the input value.
* Result is either 'email' or 'mobile'.
*
* #param string $username
* #return string
*/
public function usernameField($username)
{
return is_valid_email($username) ? 'email' : 'mobile';
}
/**
* The default file upload path.
*
* #return string|null
*/
public function uploadPath()
{
return config('base.user.upload.profile-picture.path');
}
/**
* The Staff associated with the user's id.
*
* #return \Illuminate\Database\Eloquent\Relations\hasOne
*/
public function admin()
{
return $this->hasOne(AdminDetail::class, 'user_id', 'id');
}
/**
* The Staff associated with the user's id.
*
* #return \Illuminate\Database\Eloquent\Relations\hasOne
*/
public function developer()
{
return $this->hasOne(Developer::class, 'user_id', 'id');
}
/**
* The user wallet history associated with the user's id.
*
* #return \Illuminate\Database\Eloquent\Relations\hasOne
*/
public function userWalletHistory()
{
return $this->hasMany(UserWalletHistory::class, 'user_id', 'id');
}
/**
* The favouriteLocations associated with the user's id.
*
* #return \Illuminate\Database\Eloquent\Relations\hasOne
*/
public function favouriteLocations()
{
return $this->hasMany(FavouriteLocation::class, 'user_id', 'id');
}
public function userWallet()
{
return $this->hasOne(UserWallet::class, 'user_id', 'id');
}
public function driverWallet()
{
return $this->hasOne(DriverWallet::class, 'user_id', 'id');
}
/**
* The Driver associated with the user's id.
*
* #return \Illuminate\Database\Eloquent\Relations\hasOne
*/
public function driver()
{
return $this->hasOne(Driver::class, 'user_id', 'id');
}
public function accounts()
{
return $this->hasMany(LinkedSocialAccount::class, 'user_id', 'id');
}
public function requestDetail()
{
return $this->hasMany(Request::class, 'user_id', 'id');
}
/**
* The Driver associated with the user's id.
*
* #return \Illuminate\Database\Eloquent\Relations\hasOne
*/
public function userDetails()
{
return $this->hasOne(UserDetails::class, 'user_id', 'id');
}
/**
* Get formated and converted timezone of user's created at.
*
* #param string $value
* #return string
*/
public function getConvertedCreatedAtAttribute()
{
if ($this->created_at==null||!auth()->user()->exists()) {
return null;
}
$timezone = auth()->user()->timezone?:env('SYSTEM_DEFAULT_TIMEZONE');
return Carbon::parse($this->created_at)->setTimezone($timezone)->format('jS M h:i A');
}
/**
* Get formated and converted timezone of user's created at.
*
* #param string $value
* #return string
*/
public function getConvertedUpdatedAtAttribute()
{
if ($this->updated_at==null||!auth()->user()->exists()) {
return null;
}
$timezone = auth()->user()->timezone?:env('SYSTEM_DEFAULT_TIMEZONE');
return Carbon::parse($this->updated_at)->setTimezone($timezone)->format('jS M h:i A');
}
/**
* Specifies the user's FCM token
*
* #return string
*/
public function routeNotificationForFcm()
{
return $this->fcm_token;
}
public function routeNotificationForApn()
{
return $this->apn_token;
}
protected $searchable = [
'columns' => [
'users.name' => 20,
'users.email'=> 20
],
];
/**
* The user that the country belongs to.
* #tested
*
* #return \Illuminate\Database\Eloquent\Relations\belongsTo
*/
public function countryDetail()
{
return $this->belongsTo(Country::class, 'country', 'id');
}
public function owner()
{
return $this->hasOne(Owner::class, 'user_id', 'id');
}
}
controller class
class AccountController extends ApiController
{
/**
* Get the current logged in user.
* #group User-Management
* #return \Illuminate\Http\JsonResponse
* #responseFile responses/auth/authenticated_driver.json
* #responseFile responses/auth/authenticated_user.json
*/
public function me()
{
$user = User::where('id', auth()->user()->id)->companyKey()->first();
$user = fractal($user, new UserTransformer)->parseIncludes(['onTripRequest.driverDetail','onTripRequest.requestBill','metaRequest.driverDetail','favouriteLocations']);
}
return $this->respondOk($user);
}
transfomer class
class UserTransformer extends Transformer
{
/**
* Resources that can be included if requested.
*
* #var array
*/
protected $availableIncludes = [
'roles','onTripRequest','metaRequest','favouriteLocations'
];
/**
* Resources that can be included default.
*
* #var array
*/
protected $defaultIncludes = [
'sos'
];
/**
* A Fractal transformer.
*
* #return array
*/
public function transform(User $user)
{
$params = [
'id' => $user->id,
'name' => $user->name,
'username' => $user->username,
'email' => $user->email,
'mobile' => $user->mobile,
'profile_picture' => $user->profile_picture,
'active' => $user->active,
'email_confirmed' => $user->email_confirmed,
'mobile_confirmed' => $user->mobile_confirmed,
'last_known_ip' => $user->last_known_ip,
'last_login_at' => $user->last_login_at,
'rating' => round($user->rating, 2),
'no_of_ratings' => $user->no_of_ratings,
'refferal_code'=>$user->refferal_code,
'currency_code'=>$user->countryDetail->currency_code,
'currency_symbol'=>$user->countryDetail->currency_symbol,
'map_key'=>env('GOOGLE_MAP_KEY'),
'show_rental_ride'=>true,
// 'created_at' => $user->converted_created_at->toDateTimeString(),
// 'updated_at' => $user->converted_updated_at->toDateTimeString(),
];
$referral_comission = get_settings('referral_commision_for_user');
$referral_comission_string = 'Refer a friend and earn'.$user->countryDetail->currency_symbol.''.$referral_comission;
$params['referral_comission_string'] = $referral_comission_string;
return $params;
}
/**
* Include the roles of the user.
*
* #param User $user
* #return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
*/
public function includeRoles(User $user)
{
$roles = $user->roles;
return $roles
? $this->collection($roles, new RoleTransformer)
: $this->null();
}
/**
* Include the request of the user.
*
* #param User $user
* #return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
*/
public function includeOnTripRequest(User $user)
{
$request = $user->requestDetail()->where('is_cancelled', false)->where('user_rated', false)->where('driver_id', '!=', null)->first();
return $request
? $this->item($request, new TripRequestTransformer)
: $this->null();
}
/**
* Include the request meta of the user.
*
* #param User $user
* #return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
*/
public function includeMetaRequest(User $user)
{
$request = $user->requestDetail()->where('is_completed', false)->where('is_cancelled', false)->where('user_rated', false)->where('driver_id', null)->where('is_later', 0)->first();
return $request
? $this->item($request, new TripRequestTransformer)
: $this->null();
}
/**
* Include the request meta of the user.
*
* #param User $user
* #return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
*/
public function includeSos(User $user)
{
$request = Sos::select('id', 'name', 'number', 'user_type', 'created_by')
->where('created_by', auth()->user()->id)
->orWhere('user_type', 'admin')
->orderBy('created_at', 'Desc')
->companyKey()->get();
return $request
? $this->collection($request, new SosTransformer)
: $this->null();
}
/**
* Include the favourite location of the user.
*
* #param User $user
* #return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
*/
public function includeFavouriteLocations(User $user)
{
$fav_locations = $user->favouriteLocations;
return $fav_locations
? $this->collection($fav_locations, new FavouriteLocationsTransformer)
: $this->null();
}
}
but getting error this
Type of App\Transformers\User\UserTransformer::$availableIncludes must be array (as in class League\Fractal\TransformerAbstract)
{
"success": false,
"message": "Type of App\\Transformers\\User\\UserTransformer::$availableIncludes must be array (as in class League\\Fractal\\TransformerAbstract)",
"status_code": 500,
"code": 64,
"debug": {
"line": 15,
"file": "/home/payeazyc/public_html/tagxi/app/Transformers/User/UserTransformer.php",
"class": "Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"trace": [
"#0 {main}"
]
}
}
Since starting from PHP8.* types system become more stricter, and recent version focused on the language design, some of the old principles wont work as you used to them.
In you case, look at the parent class (Transformer::class), there you will find that property $availableIncludes declared with a type of array.
In your child class( UserTransformer::class) this declaration missing on type hint level, and it causes this exception. To fix it simply add a type to your array explicitly (no doc blocs and annotations). the end result will look:
class UserTransformer extends Transformer
{
protected array $availableIncludes = [
'roles','onTripRequest','metaRequest','favouriteLocations'
];

Symfony2 - Input field type file

i wanna add a file field in my [symfony2.5] form.
I want to open the file explorer to select a file , and display his path in the view like :
"C://path/to/file.docx"
I dont want to upload a image or whatever, just the path string.
i just added that attribute in my Advert Entity :
/**
* #var string
*
* #ORM\Column(type="text", length=255, nullable=false)
* #Assert\NotBlank(message="Please, upload the product brochure as a PDF file.")
*/
private $attachment;
/**
* Set attachment
*
* #param string $attachment
* #return Advert
*/
public function setAttachment($attachment)
{
$this->title = $attachment;
return $this;
}
/**
* Get attachment
*
* #return string
*/
public function getAttachment()
{
return $this->title;
}
in my Form/AdvertType.php i've added :
->add('attachment', 'file')
Here is my addAction :
public function addAction(Request $request)
{
$advert = new Advert();
$form = $this->createForm(new AdvertType(), $advert);
$usr = $this->get('security.context')->getToken()->getUser();
if ($form->handleRequest($request)->isValid()) {
$em = $this->getDoctrine()->getManager();
$advert->setAuthor($usr->getUsername());
$advert->setDate(new \DateTime);
$em->persist($advert);
$em->flush();
$request->getSession()->getFlashBag()->add('info', 'Annonce bien enregistrée.');
// On redirige vers la page de visualisation de l'annonce nouvellement créée/
return $this->redirect($this->generateUrl('info_view', array('id' => $advert->getId())));
}
return $this->render('SocietyPerfclientBundle:Default:add.html.twig', array(
'form' => $form->createView(),
));
}
My #Assert\NotBlank(message="Please, upload the product brochure as a PDF file.") is always here..
Got this error :
I dont understand whats wrong please help me..
Don't you need a $form->isSubmitted() with your verification $form->isValid() ?
If you let #Assert\NotBlank() without message is there the "This value should not be blank" default message appearing ?

Symfony2 autocomplete search

How to create autocomplete in symfony2 that will load users from local database (one input) without using any bundle?
Here's my users entity :
<?php
namespace Me\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="Me\MainBundle\Repository\UsersRepository")
* #ORM\Table(name="users")
*/
class Users
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Assert\NotBlank(
* message = "Users first name field can not be blank!",
* groups={"registration"}
* )
* #Assert\Length(
* min = 3,
* minMessage = "First name must be at least 3 characters long!",
* groups={"registration","search"}
* )
* #ORM\Column(type="string", length=255, nullable=false, name="first_name")
*/
protected $firstName;
/**
* #Assert\NotBlank(
* message = "Users last name field can not be blank!",
* groups={"registration"}
* )
* #Assert\Length(
* min = 3,
* minMessage = "Last name must be at least 3 characters long!",
* groups={"registration","search"}
* )
* #ORM\Column(type="string", length=255, nullable=false, name="last_name")
*/
protected $lastName;
//relationship variables:
/**
* #ORM\OneToMany(targetEntity="UsersSkillLevel", mappedBy="userId")
**/
protected $usersSkillLevels;
public function __construct() {
$this->usersSkillLevels = new ArrayCollection();
}
//getters, setters:
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set firstName
*
* #param string $firstName
* #return Users
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName
*
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName
*
* #param string $lastName
* #return Users
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Add usersSkillLevels
*
* #param \Me\MainBundle\Entity\UsersSkillLevel $usersSkillLevels
* #return Users
*/
public function addUsersSkillLevel(\Me\MainBundle\Entity\UsersSkillLevel $usersSkillLevels)
{
$this->usersSkillLevels[] = $usersSkillLevels;
return $this;
}
/**
* Remove usersSkillLevels
*
* #param \Me\MainBundle\Entity\UsersSkillLevel $usersSkillLevels
*/
public function removeUsersSkillLevel(\Me\MainBundle\Entity\UsersSkillLevel $usersSkillLevels)
{
$this->usersSkillLevels->removeElement($usersSkillLevels);
}
/**
* Get usersSkillLevels
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsersSkillLevels()
{
return $this->usersSkillLevels;
}
}
And search form:
$searchForm = $this->createFormBuilder()
->setMethod('POST')
->add('user_name', 'text', array('label' => 'User\'s name: ','attr' => array('placeholder' => 'Enter Users first or last name')))
->add('searchUsers', 'submit', array('label' => 'Search for employee'))
->getForm();
It should pop when first or last name is written after 3 letters.
Thank you in advance
I think this will help you:
Two things you need to do:
1) Create a Data Transformer
hich will let you use an input field instead of the default dropdown to the linked entity.
The Data Transformer basically transforms your input (in your case a username string) to actual user object that you can store with your entity. It will let you define an input field instead of the default dropdown to the linked entity. Have a look at the documentation, it's pretty straight forward.
2) Create the Ajax autocomplete
This can be done using any library you want (jQuery, Prototype etc.) on the client side, and server side you handle this in your Controller action and replies with either JSON or a rendered template. There are plenty of tutorials for this out there. The Ajax result could include a link to create a new user, if none is found.
The Data Transformer is what you need to focus on, and I would get that working before working on the UI.
Refer bellow :
How to add an autocomplete field in forms Symfony2?

Symfony2 - Accessing tag array which has values is giving an error

I am trying to use a getTags() array which is an array of arrays into another method GetTagWeights($tags) but am getting an error when using it with this line:
$tagWeights[$tag] = (isset($tagWeights[$tag['tag']])) ? $tagWeights[$tag['tag']] + 1 : 1;
I get the following error:
ContextErrorException: Warning: Illegal offset type in /var/www/html/Satori/src/Symfony/AcmeBundle/Entity/TagRepository.php line 34
Question: What am I doing wrong here, I've dumped getTags() and there is data?
My process is getting tags then weighting the tags for popularity. Tag is setup as a ManyToMany/ManyToMany entity with a Blog entity.
getTags and getTagWeight methods (dumping $tags from getTags() returns an array of arrays)
array (size=6)
0 =>
array (size=1)
'tag' => string 'Tag 1' (length=5)
1 =>
array (size=1)
'tag' => string 'Tag 2' (length=5)
2 =>
array (size=1)
'tag' => string 'Tag 3' (length=5)
public function getTags()
{
$tags = $this->createQueryBuilder('t')
->select('t.tag')
->getQuery()
->getResult();
return $tags;
}
public function getTagWeights($tags)
{
$tagWeights = array();
if (empty($tags))
return $tagWeights;
foreach ($tags as $tag)
{
$tagWeights[$tag] = (isset($tagWeights[$tag['tag']])) ? $tagWeights[$tag['tag']] + 1 : 1;
}
// Shuffle the tags
uksort($tagWeights, function() {
return rand() > rand();
});
$max = max($tagWeights);
// Max of 5 weights
$multiplier = ($max > 5) ? 5 / $max : 1;
foreach ($tagWeights as &$tag)
{
$tag = ceil($tag * $multiplier);
}
return $tagWeights;
}
Controller
$em = $this->getDoctrine()->getManager();
$tags = $em->getRepository('AcmeBundle:Tag')
->getTags();
$tagWeights = $em->getRepository('AcmeBundle:Tag')
->getTagWeights($tags);
// var_dump($tagWeights); die();
return array(
'tags' => $tagWeights,
);
Tag entity
class Tag
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="tag", type="string", length=255)
*/
private $tag;
/**
* #ORM\ManyToMany(targetEntity="Blog", mappedBy="tags")
*/
protected $blogs;
public function __construct()
{
$this->blogs = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set tag
*
* #param string $tag
* #return Tag
*/
public function setTag($tag)
{
$this->tag = $tag;
return $this;
}
/**
* Get tag
*
* #return string
*/
public function getTag()
{
return $this->tag;
}
/**
* Add blogs
*
* #param \AcmeBundle\Entity\Blog $blogs
* #return Tag
*/
public function addBlog(\AcmeBundle\Entity\Blog $blogs)
{
$this->blogs[] = $blogs;
return $this;
}
/**
* Remove blogs
*
* #param \AcmeBundle\Entity\Blog $blogs
*/
public function removeBlog(\AcmeBundle\Entity\Blog $blogs)
{
$this->blogs->removeElement($blogs);
}
/**
* Get blogs
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBlogs()
{
return $this->blogs;
}
}
This is how I am accessing tags in twig:
{% for tag, weight in tags %}
<span class="weight-{{ weight }}">{{ tag.tag }}</span>
{% else %}
<p>There are no tags</p>
{% endfor %}
From the documentation:
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
You are trying to use $tag as key here:
$tagWeights[$tag] = (isset($tagWeights[$tag['tag']])) ? $tagWeights[$tag['tag']] + 1 : 1;
but because $tag is an array, you get an error.
I guess you wanted to do this:
$tagWeights[$tag['tag']] = (isset($tagWeights[$tag['tag']])) ? $tagWeights[$tag['tag']] + 1 : 1;

symfony 2 form entity type persisting to database value is 0

in my project i have manytomany relation between balance and cagegory table and card is join table, bellow is my code
Entity/Balance
/**
* #ORM\OneToMany(targetEntity="Card", mappedBy="balance")
*/
protected $cards;
/**
* #var integer
*
* #ORM\Column(name="category_id", type="integer")
*/
protected $categories;
-----------------------------------------------------------------------
Entity/Category
/**
* #ORM\OneToMany(targetEntity="Card", mappedBy="category")
*/
protected $cards;
-----------------------------------------------------------------------
Entity/Card
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="cards")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
/**
* #ORM\ManyToOne(targetEntity="Balance", inversedBy="cards")
* #ORM\JoinColumn(name="balance_id", referencedColumnName="id")
*/
protected $balance;
so when I want to create a balance record i should select it is belong to which category,so i try to use form entity type to fetch data from category entity and persist category id to Balance table (category_id).
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('value')
->add('categories', 'entity', array(
'class' => 'myBundle:Category',
'property' => 'name',
))
;
}
the data store but the value of category_id is 0 ????

Resources