Как экспортировать данные пользователя в формате PDF при использовании библиотеки OrgChart.Js и LaravelPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Как экспортировать данные пользователя в формате PDF при использовании библиотеки OrgChart.Js и Laravel

Сообщение Anonymous »

Привет, разработчики. У меня возникла проблема при использовании библиотеки OrgChart.Js.
Мне удалось успешно создать свою древовидную иерархическую систему, как вы можете видеть. на снимке экрана
Изображение

Это пример кода, который я использую в своем контроллере Laravel 11

Код: Выделить всё

public function showHierarchy()
{
// Fetch the admin (role_id = 3)
$admin = User::where('role_id', 3)->first();
if (!$admin) {
return 'No admin found!';
}

// Prepare the nodes array to pass to the view
$nodes = [];

// Fetch profile picture for admin
$adminProfile = Profile::where('user_id', $admin->id)->first();
$adminPic = $adminProfile ? $adminProfile->profile_pic : 'default.jpg';

// Add Admin to nodes
$nodes[] = [
'id' => $admin->id,
'name' => $admin->first_name . ' ' . $admin->last_name,
'role' => 'Admin',
'img' => asset($adminPic),
'email' => $admin->email,
'date_of_birth' => $adminProfile ? $adminProfile->date_of_birth : 'N/A',
'date_of_joining' => $adminProfile ? $adminProfile->date_of_joining : 'N/A',
'reporting_person' => 'N/A', // Admin has no reporting person
'personal_number' => $adminProfile ? $adminProfile->personal_number : 'N/A',
'address' => $adminProfile ? $adminProfile->address : 'N/A',
'pid' => 0  // Admin is the root node

];

// Fetch all users who have valid values for both team_id and team_rank
$users = User::whereNotNull('team_id')
->whereNotNull('team_rank')
->where('id', '!=', $admin->id)
->get();

foreach ($users as $user) {
// Fetch profile picture for each user
$userProfile = Profile::where('user_id', $user->id)->first();
$userPic = $userProfile ? $userProfile->profile_pic : 'default.jpg';
// Fetch the reporting person (manager)
$reportingPerson = User::where('id',$user->team_lead_id)->first();
// dd($reportingPerson->first_name);
// $reportingName = $reportingPerson ? $reportingPerson->first_name . ' ' . $reportingPerson->last_name : 'N/A';
$reportingName = '';
if ($user->team_lead_id == 0) {
$reportingName = $admin->first_name . ' ' . $admin->last_name;
$parentId = $admin->id;
} else {
$reportingPerson = User::find($user->team_lead_id);
$reportingName = $reportingPerson ? $reportingPerson->first_name . ' ' . $reportingPerson->last_name : 'N/A';
$parentId = $reportingPerson ? $reportingPerson->id : $admin->id;
}

// Determine the parent node (pid)
// If the user has team_lead_id = 0, the user reports directly to the admin
// Otherwise, the user reports to the person defined in team_lead_id (only if team_id is the same)
if ($user->team_lead_id == 0) {
// If team_lead_id is 0, user reports directly to admin
$parentId = $admin->id;
} else {
// Check if the person in team_lead_id belongs to the same team (team_id)
$teamLead = User::where('id', $user->team_lead_id)
->where('team_id', $user->team_id)  // Ensure same team
->first();

// If team_lead_id is valid, use it as parent; else, default to admin
if ($teamLead) {
$parentId = $teamLead->id;  // Reports to team lead in the same team
} else {
$parentId = $admin->id;  // If no valid team lead, report to admin
}
}

// Determine the user's role based on team_rank
$role = ($user->team_rank == 1) ? 'Manager' : (($user->team_rank == 3) ? 'Team Lead' : 'Team Member');

// Add user to the nodes array
$nodes[] = [
'id' => $user->id,
'pid' => $parentId,
'name' => $user->first_name . ' ' .  $user->last_name,
'role' => $role,
'img' => asset($userPic),
'email' => $user->email,
'date_of_birth' => $userProfile ? $userProfile->date_of_birth : 'N/A',
'date_of_joining' => $userProfile ? $userProfile->date_of_joining : 'N/A',
'reporting_person' => $reportingName,
'personal_number' => $userProfile ? $userProfile->personal_number : 'N/A',
'address' => $userProfile ? $userProfile->address : 'N/A'
];
}
// dd($nodes);
return view('test', compact('nodes'));
}
и это Js, который я использую для формулирования древовидной структуры

Код: Выделить всё

const chart = new OrgChart(document.getElementById("tree"), {
template: "isla", // Template for the tree nodes
// template: "rony", // Template for the tree nodes
nodeBinding: {
field_0: "name", // Bind "name" from your data
field_1: "role", // Bind "role" from your data
img_0: "img",
},
nodes: {!! json_encode($nodes) !!}, // Pass the $nodes array from your Laravel controller

collapse: {
level: 2, // Collapse nodes below the Manager level
allChildren: true // Collapse all children under the Managers
},
// Layout configuration
layout: OrgChart.compact,  // Use the compact layout to force horizontal alignment
siblingSeparation: 30,  // Control horizontal space between nodes
subTreeSeparation: 40,  // Space between different subtrees (managers)
nodeSize: [160, 100],  // Define node size to better fit horizontal display

// Zoom and scroll settings
zoom: {
zoomIn: true,
zoomOut: true,
fit: true
},
mouseScrool: OrgChart.action.scroll,  // Enable scrolling with mouse wheel
enableSearch: true,  // Enable search functionality
});

Теперь проблема, с которой я столкнулся, начинается, когда я нажимаю на любой узел, и он открывает боковую панель по умолчанию, как показано на снимке экрана
Изображение

Теперь, когда я нажимаю кнопку «Загрузить PDF», он загружает шаблон по умолчанию, но я хочу загрузить собственный PDF-файл одним нажатием этой же кнопки PDF. PDF-файл, который я хочу загрузить при нажатии этой кнопки, хранится в этом месте, "resources/views/card.blade.php" в моем проекте Laravel
в этом файле я хочу заполнить его некоторыми динамическими данными, такими как «Имя», «Изображение», «Дата_рождения» и т. д. Поскольку все эти данные уже передаются из контроллера и в настоящее время отображаются на боковой панели как ну


Подробнее здесь: https://stackoverflow.com/questions/791 ... ry-laravel
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»